简体   繁体   English

如何从 SQL Server 数据库绑定 ASP.NET MVC 中的下拉列表?

[英]How to bind dropdown list in ASP.NET MVC from SQL Server database?

I don't know how to make view from this code to show data in dropdown list.我不知道如何从此代码查看以在下拉列表中显示数据。 Please do tell me what changes I can make to solve my problem.请告诉我我可以做出哪些改变来解决我的问题。 I have tried some view but this causes errors.我尝试了一些视图,但这会导致错误。

Model:模型:

public class Cities
{
    public int cityid { get; set; }
    public string Description { get; set; }
}

Controller:控制器:

public ActionResult Dropdownlist()
{
    List<Citites> cityname= new List<Citites>();
    string constring = ConfigurationManager.ConnectionStrings["dbx"].ConnectionString;

    SqlConnection con = new SqlConnection(constring);

    SqlCommand cmd = new SqlCommand("SELECT Cityid, Description FROM Cities", con);

    con.Open();

    SqlDataReader rdr = cmd.ExecuteReader();

    while (rdr.Read())
    {
        Citites ci = new Citites();
        ci.cityid = Convert.ToInt32(rdr["Cityid"]);
        ci.Description = rdr[1].ToString();                
        cityname.Add(ci);
    }

    return View(cityname);
}

View:看法:

@model IEnumerable< RegisterForm_crud_mvc_.Models.Citites>
@{
    ViewBag.Title = "Dropdownlist";
}

<h2>Dropdownlist</h2>

@Html.DropDownListFor(model => model.cityid, Model.citynanme)

You have a bunch of issues in your code.您的代码中有很多问题。 Your view is strongly typed to a list of City objects and you are trying to use Model.citynanme .您的视图被强类型Model.citynanme City 对象列表,并且您正在尝试使用Model.citynanme Your model is the list of city object and the list does not have a cityname property ( but each item in the list has)!您的模型是 city 对象列表,该列表没有 cityname 属性(但列表中的每个项目都有)!

What you should ideally do is , Create a view model to represent the data needede in your view.理想情况下,您应该做的是,创建一个视图模型来表示视图中所需的数据。 In your case, you need a property to store the selected option value and another for data needed to build the options for the SELECT element.在您的情况下,您需要一个属性来存储选定的选项值,另一个用于为 SELECT 元素构建选项所需的数据。 In your case it is the list of cities.在您的情况下,它是城市列表。

public class MyViewModel
{
  public List<SelectListItem> Cities { set;get;}
  public int SelectedCityId { set;get;}
}

Now in your GET action, you create an object of this, populate the Cities property by reading your table and send the view model object to the view.现在在您的 GET 操作中,您创建一个对象,通过读取您的表来填充 Cities 属性并将视图模型对象发送到视图。

public ActionResult Create()
{
  var vm = new MyViewModel();
  vm.Cities = GetCities();
  return View(vm);
}
private List<SelectListItem> GetCities()
{
    var options = new List<SelectListItem>();
    var constring = ConfigurationManager.ConnectionStrings["dbx"].ConnectionString;
    using (var c = new SqlConnection(constring))
    {
        using (var cmd = new SqlCommand("select Cityid, Description FROM Cities", c))
        {
            c.Open();
            var rdr = cmd.ExecuteReader();
            options = new List<SelectListItem>();
            while (rdr.Read())
            {
                var o = new SelectListItem
                {
                    Value = rdr.GetInt32(rdr.GetOrdinal("Cityid")).ToString(),
                    Text = rdr.GetString(rdr.GetOrdinal("Description"))
                };
                options.Add(o);
            }
        }
    }
    return options;
}

Now in your view, which is strongly typed to MyViewModel, you will use Html.DropDownListfor helper method where you will use the Cities property as the selectList parameter.现在,在 MyViewModel 强类型化的视图中,您将使用Html.DropDownListfor helper 方法,在该方法中您将使用Cities属性作为 selectList 参数。

@model MyViewModel
@Html.DropDownListFor(model => model.SelectedCityId, Model.Cities)

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

相关问题 如何以列表形式从数据库中检索文本(SQL Server和ASP.NET MVC) - How do I retrieve text from database in list form (SQL Server & ASP.NET MVC) 如何在 ASP.NET MVC 5 中列出来自 SQL Server 的所有数据库名称? - How to list all database names from SQL Server in ASP.NET MVC 5? ASP.NET MVC下拉列表来自数据库 - ASP.NET MVC dropdown-list from database 如何从asp.net core的下拉列表中绑定数据 - How to bind data from dropdown list in asp.net core SQL Server数据库中ASP.NET MVC中的Bootstrap滑块 - Bootstrap slider in ASP.NET MVC from SQL Server database 如何从ASP.NET MVC C#中的SQL Server数据库流式传输mp3文件 - How to stream mp3 file from a SQL Server database in ASP.NET MVC C# 如何从ASP.NET MVC中的SQL Server数据库向多个收件人发送电子邮件? - How can I send email to multiple recipients from SQL Server database in ASP.NET MVC? 使用 ASP.NET MVC5 将数据从数据库导入我的视图中的下拉列表 - Importing data from database into a dropdown list in my view using ASP.NET MVC5 在 C# 和 Z9E0DA8438E1E68A1C30FVCB78 中使用 ajax 从 SQL 服务器填充下拉列表 - Populating dropdown from SQL Server with ajax in C# and ASP.NET MVC 如何使用json和ajax从asp.net中的sql server数据库填充列表 - how to populate list from sql server database in asp.net using json and ajax
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM