我想将数据从db检索到模型中并将其传递给视图
e.g。 1)db状态表,有2列Code和Text。 2)我的模特:
public class state
{
public IEnumerable<SelectListItem> list { get; set; }
public string selected { get; set; }
}
3)我希望控制器将状态表中的代码和文本数据放入列表并将选择设置为1并将模型返回到视图
如何在控制器中编写循环
答案 0 :(得分:2)
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;
}
}
理想情况下,您可以创建一个数据访问类来执行上述构造函数所做的操作,但您应该对代码有一个大概的了解。
至于Action方法:
public ActionResult StateSelect()
{
state YourViewModel = new state();
return View(YourViewModel);
}
相应的观点:
@model state
@* Add your other markup here *@
@Html.ListBoxFor(m => m.selected, Model.list)