【发布时间】:2017-04-23 21:30:14
【问题描述】:
我有一个主视图,其中包含从相应 Action 接收的数组,它还包含下面的部分视图参考
创建.cshtml:
@model HrAndPayrollSystem.Models.EmployeeMasterA
@using (Html.BeginForm())
{
ViewData["fs_lbls"] = ViewBag.FS_lbls as string[];
@Html.Partial("~/Views/EmployeeMasterA/FinalSettlementTAB.cshtml", Model)
}
上面引用的局部视图定义如下
FinalSettlementTAB.cshtml:
@model HrAndPayrollSystem.Models.EmployeeMasterA
@Html.DropDownList("DeptId", null, "Department")
/* Print "ViewData["fs_lbls"]" array defined in the Main View `Create.cshtml` here */
我在Create.cshtml 中定义了一个数组,现在,我想将它传递到部分视图HR_EmployeeFinalSettlementTAB.cshtml 并打印它,正确的方法是什么?
我尝试过的:
我将@Html.Partial() 行更改为以下内容:
@Html.Partial("~/Views/EmployeeMasterA/FinalSettlementTAB.cshtml", null, new ViewDataDictionary { { "fs_lbls", ViewData["fs_lbls"] } })
并修改 FinalSettlementTAB.cshtml 文件如下:
@model HrAndPayrollSystem.Models.EmployeeMasterA
@Html.DropDownList("DeptId", null, "Department")
@foreach (var i in ViewData["fs_lbls"] as string[])
{
@i
}
但它会在@Html.DropDownList("DeptId", null, "Department") 行抛出异常InvalidOperationException 说:
没有具有键“DeptId”的“IEnumerable”类型的 ViewData 项。
每当我尝试使用ViewDataDictionary 将数组数据传递给局部视图时,它都会引发上述异常,否则,它工作正常,而我不是。
如何摆脱上述异常并正确地将数组数据从主视图传递到部分视图?
【问题讨论】:
标签: razor asp.net-mvc-5 asp.net-mvc-partialview