![](/img/trans.png)
[英]How to pass value of drop down list to stored procedure in sqlserver in C#
[英]How to make stored procedure into a drop down list C# MVC 5
我以為我可以輕松地做到這一點,但是我遇到了錯誤,我正在嘗試在 MVC 5 中創建一個下拉列表,該列表顯示我從 SQL 存儲過程接收到的數據。 我得到了正確數量的下拉項目 (7),但是所有項目都是 SQL 數據中重復的最后一個值。 我驗證我的 SQL 存儲過程返回 7 個不同的行,其中包含我想要的不同值。
在我的模型中:
public class FindHost
{
public List<Details> Inform {get; set;}
public FindHost()
{
Inform = new List<Details>();
}
}
public class Details
{
public string HostNames {get; set;}
public string HostID {get; set;}
}
在控制器中:
public ActionResult create(int? id)
{
FindHost data = new FindHost();
Details hosts = new Details();
System.Data.SqlClient.SqlDataReader reader;
using(SqlConnection connection = new SqlConnection("..."))
{
using(SqlCommand cmd = new SqlCommand("Stored Procedure Name",connection))
{
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@Column1", 343);
cmd.Parameters.AddWithValue("@Column2", 343);
reader = cmd.ExecuteReader();
while(reader.Read())
{
hosts.HostID = reader["hostID"].Tostring();
hosts.HostNames = reader["hostName"].Tostring();
data.Inform.Add(hosts);
}
reader.Close();
}
}
ViewBag.HostStuff = new SelectList(data.Inform,"HostID", "HostNames");
return View();
}
正如@Kritner 所說:
while(reader.Read())
{
Details hosts = new Details();
hosts.HostID = reader["hostID"].Tostring();
hosts.HostNames = reader["hostName"].Tostring();
data.Inform.Add(hosts);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.