会话绑定@ Html.DropDownListFor

时间:2016-10-25 11:06:34

标签: c# asp.net asp.net-mvc razor

我在控制器中有以下方法之一

代码

        var companies = ...
        List<CompanyModel> listOfCompanies = new List<CompanyModel>();

        foreach (var item in companies)
        {
             listOfCompanies.Add(new CompanyModel(item.CompanyId, item.CompanyName));
        }

        ViewBag.Company = listOfCompanies;

查看页面

 @Html.DropDownListFor(m => m.Company, new SelectList(ViewBag.Company, "id", "name"), "Select company", new { @class = "form-control" })

这工作正常,我正在尝试使用session而不是viewbag。

所以我做了

        var companies = ...
        List<CompanyModel> listOfCompanies = new List<CompanyModel>();

        foreach (var item in companies)
        {
            listOfCompanies.Add(new CompanyModel(item.CompanyId, item.CompanyName));
        }

        Session["CompanyData"] = listOfCompanies;

查看页面

  @Html.DropDownListFor(m => m.Company, new SelectList(Model.Company, "id", "name", Session["CompanyData"]), "Select company", new { @class = "form-control" })

但这不能正常工作,是实现这个目标的路径

1 个答案:

答案 0 :(得分:1)

您是否尝试过将ViewBag替换为Session

@Html.DropDownListFor(m => m.Company, new SelectList((List<CompanyModel>)Session["CompanyData"], "id", "name"), "Select company", new { @class = "form-control" })