如何将数据库中的值绑定到MVC 4中的Dropdown List [英] How to bind value from database to Dropdown List in MVC 4
本文介绍了如何将数据库中的值绑定到MVC 4中的Dropdown List的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是我的模型
This is My Model
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;
}
}
}
}
}
怎么样在视图页面中给出
我想将它绑定到下拉列表
how to give in the view page
I want to bind it to a dropdownlist
推荐答案
你可以这样做:
这是InsertOrder类:
You can do it like so:
This is the InsertOrder class:
public class InsertOrder
{
public int CustomerId { get; set; }
public string CustomerName { get; set; }
public List<SelectListItem> SelectSource { get; set; }
public InsertOrder()
{
SelectSource = new List<SelectListItem>();
using (
var connection =
new SqlConnection(ConfigurationManager.ConnectionStrings["MyConnection"].ConnectionString))
{
using (var command = new SqlCommand("SELECT CustomerID,FirstName FROM customers", connection))
{
connection.Open();
using (var dataReader = command.ExecuteReader())
{
while (dataReader.Read())
{
var ID = new SelectListItem
{
Value = dataReader["CustomerID"].ToString(),
Text = dataReader["FirstName"].ToString()
};
SelectSource.Add(ID);
}
}
}
}
}
}
@Html.DropDownFor(model => model.CustomerId, Model.SelectSource)
既然你有一个客户ID,你最好不要在这个模型中有客户名称字段,但如果你只是不能放弃它,你可以通过jQuery拉出名字:
Now since you have a customer Id, you're better off NOT having the customer name field in this model, but if you just can't part with it, you can pull the name out via jQuery:
<script type="text/javascript">
(' #CustomerId')。select( function (){
('#CustomerId').select(function(){
(' #CustomerName')。val(
这篇关于如何将数据库中的值绑定到MVC 4中的Dropdown List的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文