在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);
}
<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>
答案 0 :(得分:4)
在MVC2中使用强类型助手时输入字段值 在发布帖子时,不会从Model属性中获取。这是 默认行为?
是的,它们首先来自ModelState,然后来自Model。如果您打算在POST操作中对模型执行某些修改,则需要先从ModelState中删除它们。例如:
[HttpPost]
public ActionResult Edit(Product p)
{
ModelState.Remove("Name");
p.Name = "prrrrrrd 2";
return View(p);
}