我今天的问题是如何在MVC 5应用程序中处理复杂的动态嵌套部分视图。这个想法是,客户可以为每次付款添加x个商店和x个商店税。
描述我的情况的最佳方式是我的模型结构:
public class PaymentViewModel
{
public HomeViewModel
{
NewStores = new List<StoreViewModel>();
}
public IList<StoreViewModel> NewStores { get; set; }
}
public class StoreViewModel
{
public StoreViewModel
{
NewStoreTax = new List<StoreTaxViewModel>();
}
public IList<StoreTaxViewModel> NewStoreTaxes { get; set; }
}
public class StoreTaxViewModel
{
public int TaxId { get; set; };
public string TaxName { get; set; };
public decimal TaxRate { get; set; };
}
视图Index.cshtml包含以下格式:
@model PaymentViewModel
@using (Html.BeginForm())
{
<div id="newStores">
@for (int i = 0; i < @Model.NewStores.Count(); i++)
{
@Html.EditorFor(model => @Model.NewStores[i])
}
<div />
<input type="button" id="addstore" name="addstore" value="Add Store" />
<input type="submit" id="submit" name="submit" value="Save" />
}
Store.cshtml的编辑器模板:
@model StoreViewModel
@using ( Html.BeginCollectionItem( "NewStores" ) )
{
<div id="newStoreTax">
@for (int i = 0; i < @Model.NewStoreTaxes.Count; i++)
{
@Html.EditorFor(model => @Model.NewStoreTaxes[i])
}
</div>
<input type="button" id="addstoretax" name="addstoretax" value="Add Store Tax" />
}
最后是StoreTax.cshtml的编辑器模板:
@model StoreTaxViewModel
@using (Html.BeginCollectionItem("StoreTaxes"))
{
<dl class="dl-horizontal">
<dt>
@Html.DisplayNameFor(model => @Model.taxName)
</dt>
<dd>
@Html.EditorFor(model => @Model.taxName)
</dd>
</dt>
@Html.DisplayNameFor( model => @Model.taxRate)
</dt>
<dd>
@Html.EditorFor(model => @Model.taxRate)
</dd>
</dl>
}
每当我发布到控制器并检查模型时,都会填充Store对象列表,但Store对象内的StoreTaxes对象列表不会。
我的控制器中有以下POST操作:
[HttpPost]
public ActionResult Index(PaymentViewModel paymentViewModel)
{
}
public ActionResult CreateNewStore()
{
var storeViewModel = new StoreViewModel();
return PartialView( "~/Views/Shared/EditorTemplates/StoreViewModel.cshtml", storeViewModel );
}
public ActionResult CreateNewStoreTax()
{
var storeTaxViewModel = new StoreTaxViewModel();
return PartialView( "~/Views/Shared/EditorTemplates/StoreTaxViewModel.cshtml", storeTaxViewModel );
}
如何构建我的应用程序来处理这种复杂的嵌套动态模板?
提前致谢!
答案 0 :(得分:0)
在您的编辑器模板中,您正在执行以下操作:
@Html.EditorFor(model => @Model.taxName)
而你应该做:
@Html.EditorFor(model => model.taxName)
此外,FWIW,您不需要为每个项目迭代调用@Html.EditorFor(model => @Model.NewStores[i])
。只是做:
@Html.EditorFor(model => model.NewStores)
Razor会自动为集合中的每个项目呈现编辑器模板。