简体   繁体   English

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

[英]How to bind a datatable to drop down list in ASP.net MVC?

I am very new to ASP.net MVC . 我是ASP.net MVC的新手。 I want to bind a dropdown with a datatable while the page is loading intitaally. 我想在页面初始加载时将下拉列表与数据表绑定。 In webforms, i used to do like: 在Web表单中,我以前喜欢这样做:

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

name and id are the column names in data table. name和id是数据表中的列名称。 I am using aspx view engine. 我正在使用aspx视图引擎。 Please help on this, 请帮忙

你在寻找类似这样

In MVC you can use the HtmlHelper DropDownListFor . 在MVC中,您可以使用HtmlHelper DropDownListFor

Suppose you havea view model like this: 假设您有一个这样的视图模型:

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

    // Some other properties..

    public int CountryId { get; set; }

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

You can generate a dropdownlist with the helper: 您可以使用助手生成一个下拉列表:

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

You will have to populate the country list in your controller: 您将必须在控制器中填充国家列表:

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();
}

If you'd wrap this dropdownlist in a form, it will post the selected country id to the controller. 如果您将此下拉列表包装为表单,它将把所选的国家/地区ID发布到控制器。

There are tons of other example around on the internet. 互联网上还有很多其他例子。 Try this one for example. 尝试这个例子。 Also, Google is your best friend. 此外,Google是您最好的朋友。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM