开发者

Dropdown list filled from repository

I have an MVC3 drop down list that come from this code on the controller.

private SelectList progCodesList = new SelectList(new[] { "Description", "Require开发者_运维知识库ments", "Development", "Testing", "Documentation" });

How can I fill the fields from a repository, to build the drop down dynamically? Thanks.


Assuming you have the progCodes in a database table, with progCode having the text, and progCodeId with a unique id, then you can read the table into a list of SelectListItem as follows:

private DbContext _db = new DbContext();

var progCodesList = _db.progCodes.Select(x => new SelectListIem()
    {
        Text = x.progCode,
        value = x.progCodeId
    }).ToList();

You can then pass this List<SelectListItem> to your view either in a strongly-typed model, or using the ViewBag.


You need to pass the progCodesList to the ViewBag in your controller method using something like:

ViewBag.ProgCodeId = progCodesList;

Then in your view, you need to fill the drop down like this:

    <div class="editor-label">
        @Html.LabelFor(model => model.ProgCodeId, "ProgCode")
    </div>
    <div class="editor-field">
        @Html.DropDownList("ProgCodeId", String.Empty)
        @Html.ValidationMessageFor(model => model.ProgCodeId)
    </div>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜