0

I have an input box in a view which is for a required date

If the user leaves this blank, the ModelState returns false and the model is returned to the view.

However, in this case, the DateTime field is then populated with the value DateTime.MinValue (01/01/0001)

How do I clear this value from the model, and return a blank inputbox?

Thanks

iabbott
  • 873
  • 1
  • 8
  • 23

3 Answers3

1

If you have not validation, then define that date as nullable in model

DateTime? AnyDate {get; set;}

So, issue will solved. When user doesn't enter AnyDate, after post it will be null. If it will not work, you can write in action:

if (!ModelState.IsValid)
{
   //control for any case
   if(model.AnyDate == DateTime.MinValue) model.AnyDate = null;      
} 
Jeyhun Rahimov
  • 3,769
  • 6
  • 47
  • 90
  • This is what I ended up doing - I didn't realize that I could have a nullable property with a [Required] annotation... now if there is nothing entered the value passed to the controller is null and it fails the validation - thanks! – iabbott Apr 02 '14 at 07:47
0

Once you are POST-ing back to your View, you will need to manipulate the values in your ModelState (not your Model) using the SetModelValue() method. Alternatively, you could Remove() the offending entry, but that has other implications (i.e., damaging your model in the ModelStateDictionary object).

For example if your data element was called RequiredDateTime, then your controller code might be:

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult ThisAction(int id, YourModel model)
{
    // Process the 'IsValid == true' condition
    if (ModelState.IsValid)
    {
        // ...
        return RedirectToAction("NextAction");
    }

    // Process the 'IsValid == false' condition
    if (ModelState.ContainsKey("RequiredDateTime"))
    {
        ModelState.SetModelValue("RequiredDateTime", new ValueProviderResult(...));
    }

    // ...

    return View(model);
}

EDIT

A little additional research turned up the following, see also:

MVC - How to change the value of a textbox in a post?

How to modify posted form data within controller action before sending to view?

I hope this helps. Good luck!

Community
  • 1
  • 1
László Koller
  • 1,139
  • 6
  • 15
0

If you want to return null value, you must edit the entity of your model to nullable as follow:

public Class MyObject
{
    String parameter {get; set;}
    DateTime? time {get; set;}
}

And if you want to change the value that the user enter before re-rendering the page with fields, you have to edit the model object to DateTime.MinValue (for instance) as follow :

    public ActionResult MyMethod(MyObject model)
    {
    if (ModelState.IsValid)
        {
        ...
        } 
    else
        {
        model.time = DateTime.MinValue; 
        }
    return View(model);
    }
clement
  • 4,204
  • 10
  • 65
  • 133