J_Boss J_Boss - 6 months ago 32
SQL Question

how to make stored procedure into a drop down list C# MVC 5

I thought I could do this easily however I'm running into an error, I'm trying to make a drop down list in MVC 5 which shows data that I have receive from a SQL stored procedure. I'm getting the correct number of drop down items (7) however all of the items are same repeated last value from the SQL data. I verify that my SQL store procedure returns 7 different rows with different values that I want.

In my model:

namespace

{
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;}
}
}
In the Controller:
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();
}

Answer

as @Kritner say:

while(reader.Read())
{
    Details hosts = new Details();

    hosts.HostID = reader["hostID"].Tostring();
    hosts.HostNames = reader["hostName"].Tostring();
    data.Inform.Add(hosts);
}
Comments