[英]Model binding not working with labelfor
这是我的模型:
public string CustomerNumber { get; set; }
public string ShipMethod { get; set; }
public string ContactPerson { get; set; }
public string ShipToName { get; set; }
public string Address1 { get; set; }
public string Address2 { get; set; }
public string Address3{ get; set; }
public string City { get; set; }
public string State { get; set; }
public string ZipCode { get; set; }
这是我的部分看法:
<table class="table table-condensed">
<thead>
<tr>
<td>Customer Number</td>
<td>Ship Method</td>
<td>Contact Person</td>
<td>Ship to Name</td>
<td>Address 1</td>
<td>Address 2</td>
<td>Address 3</td>
<td>City</td>
<td>State</td>
<td>Zip</td>
</tr>
</thead>
<tbody>
<tr>
<td>@Html.LabelFor(x => x.CustomerNumber, Model.CustomerNumber)</td>
<td>@Html.LabelFor(x => x.ShipMethod, Model.ShipMethod)</td>
<td>@Html.LabelFor(x => x.ContactPerson, Model.ContactPerson)</td>
<td>@Html.LabelFor(x => x.ShipToName, Model.ShipToName)</td>
<td>@Html.LabelFor(x => x.Address1, Model.Address1)</td>
<td>@Html.LabelFor(x => x.Address2, Model.Address2)</td>
<td>@Html.LabelFor(x => x.Address3, Model.Address3)</td>
<td>@Html.LabelFor(x => x.City, Model.City)</td>
<td>@Html.LabelFor(x => x.State, Model.State)</td>
<td>@Html.LabelFor(x => x.ZipCode, Model.ZipCode)</td>
</tr>
</tbody>
</table>
数据将正确显示在视图中,但是当我的页面上发帖时,数据返回空值。 我需要将那些LabelFors中的数据发送回我的控制器,所以我不必将其存储在会话中。 我认为MVC应该通过labelfors自动绑定到您的模型。 我究竟做错了什么?
编辑
我想我问这个问题的原因是因为我只是从Webforms迁移到了MVC,而没有viewstate的话我很迷茫。 我认为如果模型中的值始终从视图中发回给我,则无需将模型存储在会话对象中。 在我的页面上,我需要能够在页面周期内持久保存模型,以便在用户单击“保存”按钮后将模型数据存储到某些sql表中。 在MVC中将模型持久化有哪些选择?
它仅将输入元素绑定在表单内(因为浏览器发布了这些元素)。 标签未发布。
您可以使用HiddenFor
..,因为它们是输入元素:
@Html.HiddenFor(x => x.City)
..等等。 您只是不能使用标签发送回控制器。
LabelFor
:
<label></label> <!-- Not POST'ed by the browser -->
HiddenFor
:
<input type="hidden" /> <!-- POST'ed by the browser -->
MVC将按照HTML标准工作,这意味着它不会回发标签元素。
将HiddenFor
或TextboxFor
使用具有readonly
属性。
但是,如果仅显示这些值,为什么不将它们发送到页面之前放在会话中呢?
如果您有向导样式的表单,例如在将数据提交到数据库之前需要在步骤之间保存更改,那么最好的选择是将提交的值保存在会话中,然后在控制器的下一步中再次读取。 否则,您可以使用值将隐藏的输入放在表单上,但是容易被用户操纵。
像西蒙(Simon)和其他人已经解释过的,标签未发布。 要更改某些内容时,应使用发布请求。 如果您只是在查看和编辑模型,则无需将其存储在会话中。
在您看来,您将需要一个链接来编辑模型:
@Html.ActionLink("edit", "Edit", new {id = Model.CustomerNumber});
在您的控制器中实现您的Edit操作方法:
public ViewResult Edit(int customerNumber) {
var customer = _repository.Customers.FirstOrDefault(c => c.CustomerNumber == customerNumber);
return View(customer);
}
您将需要一个“编辑”操作方法的视图,然后在表单中发布更新。
@using (Html.BeginForm()) {
<label>Contact Person:</label>
<input name="ContactPerson" value="@Model.ContactPerson" />
// the rest of your form
<input type="submit" value="Save" />
}
实现处理帖子的方法。 确保添加HttpPost属性。
[HttpPost]
public ViewResult Edit(Customer customer) {
if (ModelState.IsValid) {
// Save your customer
return RedirectToAction("Index");
}
else {
return View(customer);
}
}
希望这可以帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.