Solved

MVC4 - Convert Blank Date TextBoxFor Field

Posted on 2014-10-21
10
575 Views
Last Modified: 2014-11-24
Is there a way to format null dates (01-01-1900) in MVC4

Currently, I have:
 
@if (Model.DOB == Convert.ToDateTime("01-01-1900"))
            {
                @Html.TextBoxFor(model => model.DOB, new { @Value = "", @class = "textbox150" })
            }
            else
            {
            @Html.TextBoxFor(model => model.DOB, new { @Value = Model.DOB.ToShortDateString(), @class = "textbox150" })
            }

Open in new window


But to do that for all date fields makes a lot of work.
Is there a way around this.

If so, can someone please provide a detailed example.

thanks.
0
Comment
Question by:elmbrook
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 5
  • 5
10 Comments
 
LVL 96

Expert Comment

by:Bob Learned
ID: 40397268
You could use Nullable<DateTime> (or DateTime?), and then get the value this way:

var displayDate = model.BirthDate.HasValue ? model.BirthDate.Value.ToString("yyyy-MM-dd") : "";
0
 

Author Comment

by:elmbrook
ID: 40398069
How would that work?

I get an error message when I put in
 @Html.TextBoxFor(model => model.DOB.HasValue ? model.DOB.ToString("yyyy-MM-dd") : "", new {  @class = "textbox150" })

'System.DateTime' does not contain a definition for 'HasValue' and no extension method 'HasValue' accepting a first argument of type 'System.DateTime' could be found (are you missing a using directive or an assembly reference?)
0
 
LVL 96

Expert Comment

by:Bob Learned
ID: 40398115
How is DOB defined in the model?  

You should be able to add a ? to the DateTime declaration:

Example:

public DateTime? DOB { get; set; }

Open in new window


When working with nullable value types (like int or DateTime), it can introduce other issues, but you should be able to check if the property has a value (model.DOB.HasValue).
0
[Live Webinar] The Cloud Skills Gap

As Cloud technologies come of age, business leaders grapple with the impact it has on their team's skills and the gap associated with the use of a cloud platform.

Join experts from 451 Research and Concerto Cloud Services on July 27th where we will examine fact and fiction.

 

Author Comment

by:elmbrook
ID: 40398245
I have put the code in the View, not the controller.

This is how DOB is defined.

  [EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=false)]
        [DataMemberAttribute()]
        public global::System.DateTime DOB
        {
            get
            {
                return _DOB;
            }
            set
            {
                OnDOBChanging(value);
                ReportPropertyChanging("DOB");
                _DOB = StructuralObject.SetValidValue(value);
                ReportPropertyChanged("DOB");
                OnDOBChanged();
            }
        }

Open in new window

0
 
LVL 96

Expert Comment

by:Bob Learned
ID: 40399500
You need to change it to a nullable type:

public global::System.DateTime

         becomes

public global::System.DateTime?
0
 

Author Comment

by:elmbrook
ID: 40400497
It won't allow me to do that.

I am in my model designer and when I add a question mark after it, it gives me errors (see screen shot attached).
24-10-2014-9-39-48-a-m-.jpg
0
 
LVL 96

Expert Comment

by:Bob Learned
ID: 40400675
If you are using the Entity Framework designer, then I would have thought that it generated the property type as DateTime?.  If it is not Entity Framework, then what do you use to design the data model?
0
 

Author Comment

by:elmbrook
ID: 40400692
I am using entity framework. My database table fields are all set to not null.
There are no null dates in the database, all I am trying to handle is 01-01-1900 (blank dates).
That was the only way that I could think off on handling blank dates but that means for every date I have to write that code.
I was hoping to find a better solution of handling blank dates.
0
 
LVL 96

Accepted Solution

by:
Bob Learned earned 500 total points
ID: 40402253
1) If you have to use 01-01-1900, then I would suggest changing the database fields to allow null, and use Nullable<DateTime> (DateTime?).

2) If you work in a restrictive environment, where database changes require an act of God, then translation is easy.  I would always suggest using nullable dates, but that is not set in concrete.

@Html.TextBoxFor(model => Utility.FormatDate(model.DOB, "MM/dd/yyyy")), new { @Value = "", @class = "textbox150" })

internal class Utility 
{
    public static string FormatDate(DateTime dateValue, string mask)
    {
            if (dateValue.ToString("yyyy-MM-dd") == "1900-01-01")
                return "";

            return dateValue.ToString(mask);
    }
}

Open in new window


3) Another approach is to use a View Model, and an entity mapper, like AutoMapper, where you can format the dates in all the view models, and then you wouldn't have to do any logic in the view.
0
 

Author Closing Comment

by:elmbrook
ID: 40463692
Bob - The solutions provided are just that, solutions.
I think my original solution is the way to go, it just means I have to process each date manually.

thank you for your time and input.
0

Featured Post

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This article describes a simple method to resize a control at runtime.  It includes ready-to-use source code and a complete sample demonstration application.  We'll also talk about C# Extension Methods. Introduction In one of my applications…
It was really hard time for me to get the understanding of Delegates in C#. I went through many websites and articles but I found them very clumsy. After going through those sites, I noted down the points in a easy way so here I am sharing that unde…
In this video we outline the Physical Segments view of NetCrunch network monitor. By following this brief how-to video, you will be able to learn how NetCrunch visualizes your network, how granular is the information collected, as well as where to f…
Monitoring a network: why having a policy is the best policy? Michael Kulchisky, MCSE, MCSA, MCP, VTSP, VSP, CCSP outlines the enormous benefits of having a policy-based approach when monitoring medium and large networks. Software utilized in this v…

617 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question