public class state
{
public List<SelectListItem> list { get; set; }
public string selected { get; set; }
public state()
{
SqlConnection DbConn = new SqlConnection(YourConnectionStringHere);
SqlCommand SelectStates = new SqlCommand();
SelectStates.CommandText = "select code from state";
SelectStates.Connection = DbConn;
DbConn.Open()
SqlDataReader ReadStates = SelectStates.ExecuteReader();
while (reader.Read())
list.Add(
new SelectListItem() { Text = reader[0].ToString(), Value = reader[0].ToString() });
DbConn.Close();
list[0].Selected = true;
}
}
Ideally, you could create a data access class to do what that above constructor does, but you should get the general idea of the code.
As for the Action method:
public ActionResult StateSelect()
{
state YourViewModel = new state();
return View(YourViewModel);
}
A corresponding View:
@model state
@* Add your other markup here *@
@Html.ListBoxFor(m => m.selected, Model.list)