我有一个ViewModel,它包含我的Model类型的集合,如下所示:
public class OrderConfirm
{
public ICollection<QuoteLine> SalesLines { get; set; }
public string Currency { get; set; }
public int EnquiryID { get; set; }
}
我的QuoteLine模型如下:
public class QuoteLine
{
public int QuoteLineId { get; set; }
public int LostReasonId { get; set; }
public virtual LostReason LostReason { get; set; }
public string ItemName { get; set; }
}
在我的视图中,然后我在表单中迭代这些QuoteLines中的每一个,如下所示:
@using (Ajax.BeginForm("ConfirmLostOrder", new AjaxOptions()
{
InsertionMode = InsertionMode.Replace,
UpdateTargetId = "LostOrders",
OnBegin = "LostOrderConfirm"
}))
{
<table class="completed-enq-table">
<tr>
<th>
Item Number
</th>
<th>
Reason
</th>
</tr>
@foreach (var sales in Model.SalesLines)
{
<tr>
<td>@sales.ItemName
@Html.HiddenFor(model => sales.QuoteLineID)
</td>
<td>@Html.DropDownListFor(model => sales.LostReasonId, ((IEnumerable<myApp.Models.LostReason>)ViewBag.LostReasons).Select(option => new SelectListItem
{
Text = (option == null ? "None" : option.LostReason),
Value = option.LostReasonId.ToString(),
Selected = (Model != null) && (option.LostReasonId == sales.LostStatusId)
}))
</td>
</tr>
}
</table>
<input type="submit" style="float: right;" value="Submit Lost Order" />
}
然后我的HttpPost
动作如下:
[HttpPost]
public ActionResult ConfirmLostOrder(List<QuoteLine> models)
{
// process order
return PartialView("Sales/_ConfirmLostOrder");
}
问题是,models
为空。如果我使用FormCollection
我可以看到提交的每个值,但我想使用我的模型而不是FormCollection,因为我想处理和编辑每个单独提交的行他们可能有不同的理由
答案 0 :(得分:4)
在此实例中不能使用foreach
,它必须是for
循环,以便字段的name
属性包含正确的索引,以便默认模型绑定知道它绑定到列表。
首先,我要将您的下拉值移出ViewBag
(他们应该真的在那里)。这也会在您的视图中删除一些讨厌的逻辑:)
所以你的模型现在是:
public class OrderConfirm
{
public List<QuoteLine> SalesLines { get; set; }
public string Currency { get; set; }
public int EnquiryID { get; set; }
public SelectList LostReasons { get; set; }
}
尝试此操作而不是foreach
:
@for (var i = 0; i < Model.SalesLines.Count; i++)
{
<tr>
<td>
@Model.SalesLines[i].ItemName
@Html.HiddenFor(m => m.SalesLines[i].QuoteLineId)
@Html.HiddenFor(m => m.SalesLines[i].ItemName) //assuming you want this
</td>
<td>
@Html.DropDownListFor(m => m.SalesLines[i].LostReasonId, Model.LostReasons)
</td>
</tr>
}
然后更改您的帖子方法以获取OrderConfirm
模型类型:
[HttpPost]
public ActionResult ConfirmLostOrder(OrderConfirm model)