为什么表单不能保存asp.net mvc中select的值?
本文关键字:select 的值 mvc net 表单 不能 保存 asp 为什么 | 更新日期: 2023-09-27 18:14:41
我有asp.net mvc 4项目,在剃刀视图中,我有订单列表,每个订单都是具有值和选择输入的表单。当我尝试保存实体时,我的值输入成功保存,但选择不是发送选定值,只有null。
<<p> 视图/strong>@{
ViewBag.Title = "";
Layout = "~/Views/Shared/_Layout.cshtml";
var cityRepo = new Repository<City>();
var listItemsCities = cityRepo.GetAll().Select(city => new ListItem() {
Value = city.Id.ToString(),
Text = city.Value
}).ToList();
}
@foreach (var order in Model) {
<tr>
@using (Html.BeginForm("UpdateDispatcherFromForm", "Home", FormMethod.Post)) {
@Html.AntiForgeryToken()
@Html.ValidationSummary(true)
<td>
@Html.HiddenFor(x => order.Id)
</td>
<td>
@Html.DropDownList("CityId", new SelectList(listItemsCities, "Value", "Text", order.CityId), "")
@*@if (order.City != null) {
@order.City.Value
}*@
</td>
<td>
@Html.EditorFor(x => order.Address)
@*@order.Address*@
</td>
<td>
<input type="submit" value="Save" />
</td>
}
</tr>
}
控制器[HttpPost]
public ActionResult UpdateDispatcherFromForm(Order order) {
_orderRepo.Update(order);
_orderRepo.SaveChanges();
return RedirectToAction("Dispatcher");
}
使用DropDownListFor方法代替:
http://msdn.microsoft.com/en-us/library/system.web.mvc.html.selectextensions.dropdownlistfor (v = vs.118) . aspx
根据评论中的问题进行编辑
下面是修改后的代码:
ViewBag.Title = "";
Layout = "~/Views/Shared/_Layout.cshtml";
var cityRepo = new Repository<City>();
var listItemsCities = cityRepo.GetAll().Select(city => new ListItem() {
Value = city.Id.ToString(),
Text = city.Value
}).ToList();
}
@foreach (var order in Model) {
<tr>
@using (Html.BeginForm("UpdateDispatcherFromForm", "Home", FormMethod.Post)) {
@Html.AntiForgeryToken()
@Html.ValidationSummary(true)
<td>
@Html.HiddenFor(x => order.Id)
</td>
<td>
@Html.DropDownListFor(m=>m.CityId, new SelectList(listItemsCities, "Value", "Text", order.CityId), "")
@*@if (order.City != null) {
@order.City.Value
}*@
</td>
<td>
@Html.EditorFor(x => order.Address)
@*@order.Address*@
</td>
<td>
<input type="submit" value="Save" />
</td>
}
</tr>
}
您要做的是将选择绑定到您的模型。所以,你应该使用DropDownListFor方法。
要做到这一点,你应该改变 一行 @Html.DropDownList("CityId", new SelectList(listItemsCities, "Value", "Text", order.CityId), "")
@Html.DropDownListFor(m=>m.CityId, new SelectList(listItemsCities, "Value", "Text", order.CityId), "")
请参阅这篇MSDN文章,这里的答案也是解决方案的一个很好的实现。