将ModelState.IsValid失败后,将DateTime输入框重置为空白

时间:2014-04-01 13:57:26

标签: asp.net-mvc-4 datetime

我在视图中有一个输入框,用于所需日期

如果用户将此处留空,ModelState将返回false,并且模型将返回到视图。

但是,在这种情况下,DateTime字段将填充值DateTime.MinValue(01/01/0001)

如何从模型中清除此值,并返回空白输入框?

由于

3 个答案:

答案 0 :(得分:1)

如果您尚未验证,请在模型中将该日期定义为nullable

DateTime? AnyDate {get; set;}

所以,问题将会解决。当用户未输入AnyDate时,发布后将为null。如果它不起作用,你可以写下行动:

if (!ModelState.IsValid)
{
   //control for any case
   if(model.AnyDate == DateTime.MinValue) model.AnyDate = null;      
} 

答案 1 :(得分:0)

在回到View后,您需要使用SetModelValue()方法操纵ModelState(而不是模型)中的值。或者,您可以Remove()违规条目,但这有其他含义(即,在ModelStateDictionary对象中损坏您的模型)。

例如,如果您的数据元素被称为RequiredDateTime,那么您的控制器代码可能是:

[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);
}

修改

另外一项研究发现了以下内容,另见:

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?

我希望这会有所帮助。祝你好运!

答案 2 :(得分:0)

如果要返回空值,则必须将模型的实体编辑为可为空,如下所示:

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

如果要在使用字段重新呈现页面之前更改用户输入的值,则必须将模型对象编辑为DateTime.MinValue(例如),如下所示:

    public ActionResult MyMethod(MyObject model)
    {
    if (ModelState.IsValid)
        {
        ...
        } 
    else
        {
        model.time = DateTime.MinValue; 
        }
    return View(model);
    }