ASP.NET MVC Posted date field comes in as 1/1/0001

Posted by engil on Stack Overflow See other posts from Stack Overflow or by engil
Published on 2010-04-09T16:57:42Z Indexed on 2010/04/09 17:13 UTC
Read the original article Hit count: 303

Filed under:
|

Just started working with .NET and MVC(1). I'm having a problem wherein in my add action the entered date for some reason ends up as 1/1/0001 instead of what is entered thus causing a date overflow.

In my model, this field ("Added") is is of type datetime and does not allow nulls.

In my controller I have:

public ActionResult Add()
    {
        Instance instance = new Instance()
        {
            Added = DateTime.Now,
            Active = true
        };

        return View(instance);
    }

    [AcceptVerbs(HttpVerbs.Post)]
    public ActionResult Add(Instance instance)
    {

        if (ModelState.IsValid)
        {
            try
            {
                System.Diagnostics.Trace.Write("test");
                instanceRepository.Add(instance);
                instanceRepository.Save();

                return RedirectToAction("Details", new { id = instance.InstanceID });
            }
            catch
            {
                ModelState.AddRuleViolations(instance.GetRuleViolations());
            }
        }
        return View(instance);
    }

And in my view I have:

        <div class="editor-label">
            <%= Html.LabelFor(model => model.Added) %>
        </div>
        <div class="editor-field">
            <%= Html.TextBoxFor(model => model.Added,String.Format("{0:g}",Model.Added))%>
            <%= Html.ValidationMessageFor(model => model.Added) %>

When I first go to Instances/Add the default value is set correctly, however as soon as I submit the date turns into 1/1/0001 (from my understanding this indicates that it was either null or in an unrecognizable format)

When I debug and palce a watch on Request.Form I see the date coming in encoded ie Request.Form {Added=4%2f9%2f2010+8%3a24%3a39+AM} - is this an issue?

I know its probably not enough information to make a conlusive determination on why this is failing, but if someone could provide some good debugging tips on how to determine where the submitted date is getting munged I'd really appreciate it.

© Stack Overflow or respective owner

Related posts about ASP.NET

Related posts about asp.net-mvc