我想知道 MVC 3 中是否可以实现以下操作
我基本上有一个带有子集合的 ViewModel,我想使用 Ajax 表单发布它:
型号
[Serializable]
public class Customer
{
public string FirstName { get; set; }
public string LastName { get; set; }
public int CurrentSalesRep { get; set; }
public List<SelectListItem> SalesReps { get; set; }
}
[Serializable]
public class CustomerVM
{
public List<Customer> Customers { get; set; }
}
销售 Controller
[HttpPost]
public ActionResult Customers(CustomerVM customer)
{
return PartialView(customer);
}
查看
@model DropdownSave.Models.CustomerVM
<div>
@{
using(Ajax.BeginForm("Customers", "Sales", new AjaxOptions { UpdateTargetId = "gridArea",HttpMethod="Post" })){
<div id="gridArea">
<table>
@foreach (var m in Model.Customers)
{
<tr>
<td>
@Html.TextBoxFor(a => m.FirstName)
</td>
<td>
@Html.TextBoxFor(a => m.LastName)
</td>
</tr>
}
</table>
<input type="submit" value="Save" />
</div>
}
}
</div>
基本上,我可以将 CustomerVm 的实例发布到 Controller ,但子集合为空。我正在尝试的事情可能吗?
最佳答案
我自己解决了:
看起来 View 必须更新为以下内容
<div>
@{
using(Ajax.BeginForm("Customers", "Sales", new AjaxOptions { UpdateTargetId = "gridArea",HttpMethod="Post" })){
<div id="gridArea">
<table>
@for (int i = 0; i < Model.Customers.Count; i++)
{
<tr>
<td>
@Html.LabelFor(m => m.Customers[i].FirstName)
</td>
<td>
@Html.LabelFor(m => m.Customers[i].LastName)
</td>
<td>
@Html.HiddenFor(m => m.Customers[i].CurrentSalesRep)
</td>
<td>
@Html.DropDownListFor(m => m.Customers[i].CurrentSalesRep,Model.Customers[i].SalesReps)
</td>
</tr>
}
</table>
<input type="submit" value="Save" />
</div>
}
}
</div>
我还添加了捕获下拉列表中所选项目的功能
关于c# - 提交带有子集合的 View 模型的表单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10050103/