asp.net-mvc-3 - MVC3、Razor View 、EditorFor、查询字符串值覆盖模型值

标签 asp.net-mvc-3

我有一个需要 DateTime 的 Controller 操作?通过查询字符串作为后重定向获取的一部分。 Controller 看起来像例如

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

我的模型是:
public class IndexModel
{
    [DataType(DataType.Date)]
    [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd MMM yyyy}")]
    public DateTime Date { get; set; }
}

Razor 的观点是:
@model Mvc3Playground.Models.Home.IndexModel

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

我的问题有两个:

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

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

有任何想法吗?

最佳答案

Html 助手在绑定(bind)时首先使用 ModelState,因此如果您打算修改 Controller 操作中模型状态中存在的某些值,请确保首先将其从 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);
}

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

这是发生的事情:
  • 当您请求/Home/Index 时,ModelState 中没有任何内容,因此 Html.EditorFor(x => x.Date)助手使用您的 View 模型的值(您已设置为 DateTime.Now ),当然它会应用正确的格式
  • 当您请求 /Home/Index?date=1/1/1 , Html.EditorFor(x => x.Date)助手检测到有 date ModelState 内的变量等于 1/1/1它使用这个值,完全忽略存储在 View 模型中的值(这在 DateTime 值方面几乎相同,但当然没有应用格式)。
  • 关于asp.net-mvc-3 - MVC3、Razor View 、EditorFor、查询字符串值覆盖模型值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7541328/

    相关文章:

    asp.net-mvc-3 - 无法验证用户时如何返回更详细的错误

    javascript - 如何将javascript对象映射到mvc模型?

    asp.net-mvc-3 - 如果 Controller.OnAuthorization() 返回 void 那么我如何拒绝访问?

    asp.net-mvc - 在 ASP.NET MVC 中持久化非表单模型数据

    javascript - MVC Razor 应用程序中的 SignalR javascript

    c# - 如何在来自 View 的 View 值中显示标签

    entity-framework - EF4 和 MVC3 - 我需要存储库模式吗?

    asp.net-mvc - 在mvc中使用ajax调用重定向到另一个 View

    asp.net-mvc-3 - 如何从 @Html.EditForModel() 中排除字段,但使用 Html.DisplayForModel() 显示该字段

    asp.net-mvc-3 - 什么是 ASP.NET MVC 中服务层的好例子?