MrM
MrM

Reputation: 21999

How to Convert to DateTime on HTML.Textbox?

I have a textbox that should accept datetime formats only. I am not sure how to convert this in MVC. I also want to know how to rearrange to a "yyyyMMdd" format, which is what needs to be passed.

<%=Html.TextBox("effectiveDate") %> 

My controller has nothing :X

public ActionResult Index()
{
     return View();
}

I know I am missing something... what is it?

I am not worried about entering a bad date right now... I just want to get the conversion concept.

Upvotes: 1

Views: 4077

Answers (3)

MrM
MrM

Reputation: 21999

I will give this on to Robert, but after looking at his link. I started off with a simple solution...

<%=Html.TextBox("effectiveDate", String.Format("{0:g}", DateTime.Now)) %>

I didnt want to do any backend processing until after the date so a simple return view() was good enough, for what I was trying to do. Thanks again Robert

Upvotes: 0

Robert Harvey
Robert Harvey

Reputation: 180788

For a strongly-typed model:

<%= Html.TextBox("effectiveDate", Model.effectiveDate.ToString("yyyyMMdd")) %> 

If it's not a strongly-typed model (i.e. you have it in the ViewData), try this:

<%= Html.TextBox("effectiveDate", 
    ((DateTime)ViewData.EffectiveDate).ToString("yyyyMMdd")) %> 

To demonstrate using the second method, change your controller code to this:

public ActionResult Index()
{
     ViewData("EffectiveDate") = DateTime.Now;
     return View();
}

Make sure you check out the NerdDinner tutorials at http://nerddinnerbook.s3.amazonaws.com/Intro.htm

Upvotes: 3

dove
dove

Reputation: 20674

@Robert's answer is valid. However if you are using strongly typed ViewModels and this is a readonly view then I would suggest property be a string and setting format before view is bound.

If it is an editable form then a DateTime property would probably be more appropriate.

I use AutoMapper to flatten my domain entities in different views and make use of the following DateTime converter (which makes it consistant for all english speaking cultures, you might have to consider culture more if your audience is wider)

public class DateTimeTypeConverter : ITypeConverter<DateTime, string>
        {
            public string Convert(DateTime source)
            {
                return source.ToString("dd-MMM-yyyy");
            }
        }

Upvotes: 0

Related Questions