我在检索表单集合中的选择列表的值时遇到问题。我尝试使用与选择列表同名的属性创建一个viewmodel。
老实说,我真的意识到我真的不明白模型绑定如何与选择列表一起使用。我刚刚假设适用以下约定:
除此之外,我真的不明白。我看过几本关于它的书,坦率地说它们毫无用处。
选择列表如何与a)表单集合和b)特定模型一起使用?
答案 0 :(得分:2)
以下是一个例子:
型号:
public class MyViewModel
{
public string SelectedItemValue { get; set; }
public IEnumerable<SelectListItem> Items { get; set; }
}
控制器:
public class HomeController: Controller
{
public ActionResult Index()
{
var model = new MyViewModel
{
// TODO: Fetch those from a repository
Items = new SelectList(
new[]
{
new SelectListItem { Value = "1", Text = "Item 1" },
new SelectListItem { Value = "2", Text = "Item 2" },
new SelectListItem { Value = "3", Text = "Item 3" },
},
"Value",
"Text"
)
};
}
[HttpPost]
public ActionResult Index(string selectedItemValue)
{
// Here you get the selected value from the dropdown
return ...
}
}
查看:
<% using (Html.BeginForm()) { %>
<%= Html.DropDownListFor(x => x.SelectedItemValue, Model.Items)
<input type="submit" value="OK" />
<% } %>