Html.DropDownList不显示SelectList选择值

时间:2017-01-16 11:34:22

标签: c# asp.net asp.net-mvc html.dropdownlistfor selectlist

我已经阅读了很多有关该主题的问题,但未能找到解决此特定问题的方法。

控制器

public ActionResult Index() {
    string categorie = "--Tout--";
    string souscategorie = "--Tout--";

    if (Session["Categorie"] != null) {
        categorie = Session["Categorie"].ToString();
    }

    if (Session["SousCategorie"] != null) {
        souscategorie = Session["SousCategorie"].ToString();
    }

    SelectList cats = new SelectList(GetCategories(), categorie);
    SelectList sCats = new SelectList(GetSousCategories(), souscategorie);

    ViewBag.Categories = cats;
    ViewBag.SousCategories = sCats;

    using(DAL.WebShopEntities entities = new WebShopEntities()) {
        return View(entities.Article.ToList());
    }
}

视图

@Html.Label("Catégories")
@Html.DropDownList("Categories", (SelectList)ViewBag.Categories, new { @class = "form-control dropdownlist" })

<br />

@Html.Label("Sous-Catégories")
@Html.DropDownList("SousCategories", (SelectList)ViewBag.SousCategories, new { @class = "form-control dropdownlist" })

调试视图时,我可以清楚地看到会话中存储的选项被发送到视图。但是在检入浏览器时它会显示索引0。这让我烦恼,因为SelectList行为正常,我认为这个问题与DropDown有关,但可能是什么问题呢?

1 个答案:

答案 0 :(得分:0)

您可以尝试更改Viewbag属性名称,然后重试吗?

尝试类别=&gt; CategoriesList 和     的 SousCategories =&GT; SousCategoriesList

public ActionResult Index() {
    string categorie = "--Tout--";
    string souscategorie = "--Tout--";

    if (Session["Categorie"] != null) {
        categorie = Session["Categorie"].ToString();
    }

    if (Session["SousCategorie"] != null) {
        souscategorie = Session["SousCategorie"].ToString();
    }

    SelectList cats = new SelectList(GetCategories(), categorie);
    SelectList sCats = new SelectList(GetSousCategories(), souscategorie);

    ViewBag.CategoriesList = cats;
    ViewBag.SousCategoriesList = sCats;

    using(DAL.WebShopEntities entities = new WebShopEntities()) {
        return View(entities.Article.ToList());
    }
}



@Html.Label("Catégories")
@Html.DropDownList("Categories", (SelectList)ViewBag.CategoriesList, new { @class = "form-control dropdownlist" })

<br />

@Html.Label("Sous-Catégories")
@Html.DropDownList("SousCategories", (SelectList)ViewBag.SousCategoriesList, new { @class = "form-control dropdownlist" })