如何在asp.net mvc 5中将数组从主视图传递到局部视图

时间:2016-12-08 15:21:28

标签: razor asp.net-mvc-5 asp.net-mvc-partialview

我的主视图包含从相应的Action收到的数组,它还包含下面的部分视图参考

Create.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
}

但它会在行InvalidOperationException处抛出异常@Html.DropDownList("DeptId", null, "Department"),说:

  

没有类型' IEnumerable'的ViewData项目。有关键的' DeptId'。

每当我尝试使用ViewDataDictionary将数组数据传递到局部视图时,它会抛出上述异常,否则,它正常工作,当我没有。

如何摆脱上述异常并将数组数据从主视图正确传递到局部视图?

1 个答案:

答案 0 :(得分:1)

我建议您向.nav-tabs{ display: flex; } .nav-tabs li { display: flex; flex: 1; } .nav-tabs li a { flex: 1; } 添加新属性以存储标签,这样您根本不需要使用EmployeeMasterA

ViewData

<强> Create.cshtml

public class EmployeeMasterA
{
    public string[] fs_lbls { get; set; }

    public string SelectedLabel { get; set; }

    public List<SelectListItem> Labels
    {
        get
        {

            if (this.fs_lbls == null)
            {
                return Enumerable.Empty<SelectListItem>().ToList();
            }

            return (from label in fs_lbls
                   select new SelectListItem
            {
                Text = label,
                Value = label
            }).ToList();
        }
    }
}

<强> FinalSettlementTAB.cshtml

@model WebApplication1.Controllers.EmployeeMasterA

@using (Html.BeginForm())
{
    @Html.Partial("FinalSettlementTAB", Model)
    <input type="submit" value="Save"/>
}

控制器

@model WebApplication1.Controllers.EmployeeMasterA

@Html.DropDownList("SelectedLabel", Model.Labels)

在返回public ActionResult Create() { var viewModel = new EmployeeMasterA(); viewModel.fs_lbls = new[] {"Label1", "label 2"}; return View(viewModel); } [HttpPost] public ActionResult Create(EmployeeMasterA viewModel) { return View(); } 视图之前,您可以在控制器操作方法中设置fs_lbls的内容。发布表单时,Create属性将包含下拉列表中的所选项目。显然,您需要更改属性名称以满足您的需求,但希望这会给您一个想法。