此:
string val = Convert.ToString(Model.gender);
ViewData["gen"] = val;
是不与此兼容:
ViewData["gen"] as SelectList
ViewData["gen"]
包含一个字符串值,而不是SelectList
,当你尝试投它,你得到空和下拉不包含任何值。
您需要一个数组才能填充下拉列表。第一步是创建一个强类型的对象数组。假设你有下面的类定义:
public class Gender
{
public int Id { get; set; }
public int Text { get; set; }
}
在你的控制器动作:
public ActionResult Index()
{
var genderList = new[]
{
new Gender{ Id = 1, Text = "Male" },
new Gender{ Id = 2, Text = "Female" },
}; // This should come from the database
ViewData["genderList"] = new SelectList(genderList, "Id", "Text");
return View();
}
,并在视图:
<%= Html.DropDownList("gen", ViewData["genderList"] as SelectList) %>
我没有得到,如何从已存储的数据库中获取值。我想显示在顶部的价值。 – Renu123 2010-05-18 15:03:59