MVC3,Razor视图,EditorFor,查询字符串值会覆盖模型值

mag*_*tte 4 asp.net-mvc-3

我有一个控制器动作,需要一个DateTime?通过查询字符串作为post-redirect-get的一部分.控制器看起来像例如

public class HomeController : Controller
{
    [HttpGet]
    public ActionResult Index(DateTime? date)
    {
        IndexModel model = new IndexModel();

        if (date.HasValue)
        {
            model.Date = (DateTime)date;
        }
        else
        {
            model.Date = DateTime.Now;
        }

        return View(model);
    }

    [HttpPost]
    public ActionResult Index(IndexModel model)
    {
        if (ModelState.IsValid)
        {
            return RedirectToAction("Index", new { date = model.Date.ToString("yyyy-MM-dd hh:mm:ss") });
        }
        else
        {
            return View(model);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我的模型是:

public class IndexModel
{
    [DataType(DataType.Date)]
    [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd MMM yyyy}")]
    public DateTime Date { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

Razor的观点是:

@model Mvc3Playground.Models.Home.IndexModel

@using (Html.BeginForm()) {
    @Html.EditorFor(m => m.Date);
    <input type="submit" />
}
Run Code Online (Sandbox Code Playgroud)

我的问题有两个问题:

(1)如果查询字符串包含date的值,则使用[DisplayFormat]属性在模型上应用的日期格式不起作用.

(2)模型中保存的值似乎被查询字符串值包含的任何内容覆盖.例如,如果我在Index GET操作方法中设置了一个断点,并手动设置等于今天的日期,如果查询字符串包含例如?date = 1/1/1,则显示"1/1/1"文本框(计划是验证日期,如果查询字符串1无效,则默认为日期).

有任何想法吗?

Dar*_*rov 14

Html帮助程序在绑定时首先使用ModelState,因此如果您打算修改控制器操作中模型状态中存在的某些值,请确保首先将其从ModelState中删除:

[HttpGet]
public ActionResult Index(DateTime? date)
{
    IndexModel model = new IndexModel();

    if (date.HasValue)
    {
        // Remove the date variable present in the modelstate which has a wrong format
        // and which will be used by the html helpers such as TextBoxFor
        ModelState.Remove("date");
        model.Date = (DateTime)date;
    }
    else
    {
        model.Date = DateTime.Now;
    }

    return View(model);
}
Run Code Online (Sandbox Code Playgroud)

我必须同意这种行为不是很直观,但它是设计的,所以人们应该真正习惯它.

这是发生的事情:

  • 当您请求/ Home/Index时,ModelState内部没有任何内容,因此Html.EditorFor(x => x.Date)帮助程序使用您的视图模型的值(您已设置DateTime.Now),当然它应用了正确的格式
  • 当你请求时/Home/Index?date=1/1/1,Html.EditorFor(x => x.Date)帮助器检测到一个date变量在内部ModelState等于1/1/1并且它使用了这个值,完全忽略了视图模型中存储的值(就DateTime值来说几乎相同但当然没有应用格式化) .