MVC表單無法發(fā)布對象列表所以我有一個MVC ASP.NET應(yīng)用程序有問題。本質(zhì)上,我有一個視圖,它包含一個表單,它的內(nèi)容被綁定到一個對象列表中。在這個循環(huán)中,它加載PartialView中正在循環(huán)的項?,F(xiàn)在一切都在運轉(zhuǎn),直到形體被提交。當(dāng)提交時,控制器將被發(fā)送一個空對象列表。下面的代碼證明了這些問題。家長意見:@model IEnumerable<PlanCompareViewModel>@using (Html.BeginForm("ComparePlans", "Plans", FormMethod.Post, new { id = "compareForm" })){<div>
@foreach (var planVM in Model)
{
@Html.Partial("_partialView", planVM)
}</div>}_ParalView:@model PlanCompareViewModel<div>
@Html.HiddenFor(p => p.PlanID)
@Html.HiddenFor(p => p.CurrentPlan)
@Html.CheckBoxFor(p => p.ShouldCompare)
<input type="submit" value="Compare"/></div>以下是上述代碼的類:PlanViewModel:public class PlansCompareViewModel{
public int PlanID { get; set; }
public Plan CurrentPlan { get; set; }
public bool ShouldCompare { get; set; }
public PlansCompareViewModel(Plan plan)
{
ShouldCompare = false;
PlanID = plan.PlanId;
CurrentPlan = plan;
}
public PlansCompareViewModel()
{
// TODO: Complete member initialization
}
public static IEnumerable<PlansCompareViewModel> CreatePlansVM(IEnumerable<Plan> plans)
{
return plans.Select(p => new PlansCompareViewModel(p)).AsEnumerable();
}}主計長:public class PlansController : MyBaseController{
[HttpPost]
public ActionResult ComparePlans(IEnumerable<PlanCompareViewModel> model)
{
//the model passed into here is NULL
}}問題在于控制器的作用。據(jù)我所知,它應(yīng)該發(fā)布一個PlanCompareViewModel的可枚舉列表,但它是空的。在檢查發(fā)送的POST數(shù)據(jù)時,它發(fā)送的是正確的Params。如果我要將‘IEnDigable’改為‘FormCollection’,它包含正確的值。有人知道為什么綁定器沒有創(chuàng)建正確的對象嗎?我可以使用javascript繞過這個問題,但這違背了目的!任何幫助都將不勝感激!
2 回答

largeQ
TA貢獻(xiàn)2039條經(jīng)驗 獲得超8個贊
null
@foreach (var planVM in Model){ @Html.Partial("_partialView", planVM)}
<input type="hidden" name="yourmodelprefix.PlanID" /><input type="hidden" name="yourmodelprefix.CurrentPlan" /><input type="checkbox" name="yourmodelprefix.ShouldCompare" />
<input type="hidden" name="yourmodelprefix[0].PlanID" /><input type="hidden" name="yourmodelprefix[0].CurrentPlan" /><input type="checkbox" name="yourmodelprefix[0].ShouldCompare" /><input type="hidden" name="yourmodelprefix[1].PlanID" /><input type="hidden" name="yourmodelprefix[1].CurrentPlan" /><input type="checkbox" name="yourmodelprefix[1].ShouldCompare" />
創(chuàng)建一個 EditorTemplates
視圖當(dāng)前文件夾中的文件夾(例如,如果您的視圖是 Home\Index.cshtml
,創(chuàng)建文件夾 Home\EditorTemplates
).在該目錄中創(chuàng)建一個強類型視圖,其名稱與您的模型相匹配。在你的情況下 PlanCompareViewModel.cshtml
.
@model PlanCompareViewModel<div> @Html.HiddenFor(p => p.PlanID) @Html.HiddenFor(p => p.CurrentPlan) @Html.CheckBoxFor(p => p.ShouldCompare) <input type="submit" value="Compare"/></div>
@model IEnumerable<PlanCompareViewModel>@using (Html.BeginForm("ComparePlans", "Plans", FormMethod.Post, new { id = "compareForm" })){<div> @Html.EditorForModel()</div>}
DisplayTemplates
EditorTemplates
- 2 回答
- 0 關(guān)注
- 469 瀏覽
添加回答
舉報
0/150
提交
取消