views:

349

answers:

3

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.

+3  A: 

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

Robert Harvey
It seem this is what I am looking for, but my controller just has return view(). Where am I messing up???
I edited my answer to add some controller code, so you can see it in action.
Robert Harvey
I think your right, but i cant seem to get the viewdata to work..
Thanks!!! I think I got some help with the help of the link you had
A: 

@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");
            }
        }
dove
A: 

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

I put the date in the controller because that's where it would go if you were looking up the date from a repository, but your method works fine if you just want to display the current date and time.
Robert Harvey