如何在View中实现DropDownListFor?

时间:2017-08-13 03:53:41

标签: asp.net-mvc html-helper

我想在HtmlHelper的Create View中的下拉列表中显示“Category”的所有名称。

“类别”模型是:

public class Category
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }
}

控制器是:

public ActionResult Create()//
{
    ViewBag.Categorys = new SelectList(categoryRepo.SelectAll(), "Id", "Name");
    return View();
}

视图是:

<div class="form-group">
    @Html.LabelFor(model => model.CategoryId, htmlAttributes: new { @class = "control-label col-md-2" })
    <div class="col-md-10">
        @Html.DropDownListFor(model => model.CategoryId, (SelectList)ViewBag.Categorys, new { htmlAttributes = new { @class = "form-control" } })
        @Html.ValidationMessageFor(model => model.CategoryId, "", new { @class = "text-danger" })
    </div>
</div>

1 个答案:

答案 0 :(得分:-2)

你可以试试这个,

@Html.DropDownList("Categorys", null, "Select Category", new {@class="form-control"})