如何将数据表绑定到ASP.net MVC中的下拉列表?

问题描述 投票:2回答:2

我是ASP.net MVC的新手。我希望在页面正在加载时将下拉列表与数据表绑定。在webforms中,我曾经这样做:

dropdownname.datasource=dt;
dropdownname.textfield="name";
dropdownname.valuefield="id";

name和id是数据表中的列名。我正在使用aspx视图引擎。请帮忙,

c# asp.net-mvc html-select
2个回答
3
投票

你在寻找像this这样的东西吗?


1
投票

在MVC中,您可以使用HtmlHelper DropDownListFor

假设你有一个像这样的viewmodel:

public class UserModel
{
    public string Name { get; set; }

    // Some other properties..

    public int CountryId { get; set; }

    public IEnumerable<SelectListItem> Countries { get; set; }
}

您可以使用帮助程序生成下拉列表:

@Html.DropDownListFor(m => m.CountryId, Model.Countries)

您必须填充控制器中的国家/地区列表:

public ActionResult Edit(int userId)
{
    var model = new UserModel();
    // get data from db.

    // Populate countries list.
    model.Countries = db.Countries.Select(c => new SelectListItem
                                                   {
                                                        Value = c.Id,
                                                        Text = c.Name
                                                   }).ToList();
}

如果您将此下拉列表包装在表单中,它会将选定的国家/地区ID发布到控制器。

互联网上还有很多其他的例子。以this one为例。此外,谷歌是你最好的朋友。

© www.soinside.com 2019 - 2024. All rights reserved.