【问题标题】:asp.net-mvc2 - Strongly typed helpers not using Model?asp.net-mvc2 - 不使用模型的强类型助手?
【发布时间】:2011-11-02 02:46:46
【问题描述】:

在 MVC2 中使用强类型帮助器时,在发布帖子时输入字段值不会从 Model 属性中获取。这是默认行为吗?

(强类型)具有强类型助手的视图:

<div class="editor-label">
    <%: Html.LabelFor(model => model.Name) %>
</div>
<div class="editor-field">
    <%: Html.TextBoxFor(model => model.Name) %>
    <%: Html.ValidationMessageFor(model => model.Name) %>
</div>

<div class="editor-label">
    <%: Html.LabelFor(model => model.Price) %>
</div>
<div class="editor-field">
    <%: Html.TextBoxFor(model => model.Price) %>
    <%: Html.ValidationMessageFor(model => model.Price) %>
</div>

控制器操作:/Product/Edit/5

    public ActionResult Edit(int id)
    {
        var p = new Product();
        p.Name = "product 1";
        p.Price = "100";
        return View(p);
    }

HTML 输出:

<div class="editor-label">
    <label for="Name">Name</label>
</div>

<div class="editor-field">
    <input id="Name" name="Name" type="text" value="product 1" />
</div>

<div class="editor-label">
    <label for="Price">Price</label>
</div>
<div class="editor-field">
    <input id="Price" name="Price" type="text" value="100" />
</div>

控制器操作:/Product/Edit/5

    [HttpPost]
    public ActionResult Edit(Product p)
    {
        p.Name = "prrrrrrd 2";
        return View(p);

    }

表单发布后的 HTML 输出(下面我希望 id="Name" 的输入值是“prrrrrrd 2。强类型帮助器从哪里获得它的值?):

<div class="editor-label">
    <label for="Name">Name</label>
</div>

<div class="editor-field">
    <input id="Name" name="Name" type="text" value="product 1" />
</div>

<div class="editor-label">
    <label for="Price">Price</label>
</div>
<div class="editor-field">
    <input id="Price" name="Price" type="text" value="100" />
</div>

【问题讨论】:

    标签: asp.net-mvc-2 modelstate strongly-typed-helper


    【解决方案1】:

    在 MVC2 中使用强类型助手时,输入字段值 发布帖子时不会从 Model 属性中获取。这是 默认行为?

    是的,它们首先取自 ModelState,然后取自 Model。如果您打算在 POST 操作中对模型执行一些修改,则需要先将它们从 ModelState 中删除。例如:

    [HttpPost]
    public ActionResult Edit(Product p)
    {
        ModelState.Remove("Name");
        p.Name = "prrrrrrd 2";
        return View(p);
    }
    

    【讨论】:

    • 我不记得以前的项目中的这一点。 ModelState 是否有可能在以前的“版本”中被禁用或某些东西?
    • @ReFocus,不确定您所说的以前的项目是什么意思。如果你的意思是 ASP.NET MVC 1.0,那么,没有强类型的帮助器(一个以 For 结尾并将 lambda 表达式作为第一个参数的)。
    • 我刚刚仔细检查了一遍。 “默认”助手还在 Model 值之前使用 ModelState。这种行为在 MVC2 中是新的吗?
    • @ReFocus,是的,这是默认行为。这是设计使然,而且一直都是这样。
    猜你喜欢
    • 2011-01-05
    • 1970-01-01
    • 2011-04-30
    • 1970-01-01
    • 1970-01-01
    • 2011-03-23
    • 1970-01-01
    • 1970-01-01
    • 2012-03-10
    相关资源
    最近更新 更多