如何将数据库中的值绑定到MVC 4中的Dropdown List

时间:2014-11-13 10:57:14

标签: asp.net-mvc

这是我的模特

public class InsertOrder
{
    public int CustomerId { get; set; }
    public string CustomerName { get; set; }     
}

public List<InsertOrder> getcustomerid()
{
    List<InsertOrder> customerlist = new List<InsertOrder>();
    SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["MyConnection"].ConnectionString);
    SqlDataReader Datareader;
    {
        using (SqlCommand command = new SqlCommand("SELECT CustomerID,FirstName FROM customers", connection))
        {
            connection.Open();
            Datareader = command.ExecuteReader();
            while (Datareader.Read())
            {
                InsertOrder ID = new InsertOrder();
                ID.CustomerId = Convert.ToInt32(Datareader["CustomerID"]);
                ID.CustomerName = Datareader["FirstName"].ToString();

                customerlist.Add(ID);
            }
            Datareader.Close();
            return customerlist;
        }
    }
}

如何在视图页面中提供

1 个答案:

答案 0 :(得分:0)

            public ActionResult Index()
            {
                var customerList = new InsertOrder().getcustomerid();

                ViewBag.CustomerList = new SelectList(customerList, "CustomerId",CustomerName") ;
                return View(YourModel);
            }

观看

@Html.DropDownListFor(m => m.SampleDropDownValue, Model.CustomerList , "--Select--")