1

在 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>
4

1 回答 1

4

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

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

[HttpPost]
public ActionResult Edit(Product p)
{
    ModelState.Remove("Name");
    p.Name = "prrrrrrd 2";
    return View(p);
}
于 2011-08-23T16:22:17.247 回答