ASP.NET MVC的DropDownList [英] ASP.NET MVC dropdownlist
问题描述
有人点我到显示DropDownList的LINQ从人口正在向SQL(文本和值被设置)。
Can someone point me to an article that shows the dropdownlist being populated from linq to sql (text and value being set).
谢谢
丹尼
推荐答案
现在的的HtmlHelper扩展需要一个的IEnumerable< SelectListItem>
,我没有创建的SelectList的,但通常只是创建SelectListItems使用LINQ。
Now that the HtmlHelper extension takes an IEnumerable<SelectListItem>
, I don't create SelectList's, but usually just create the SelectListItems with LINQ.
控制器
ViewData["CategoryID"] = categories.Select( c => new SelectListItem
{
Text = c.CategoryName,
Value = c.CategoryID
}
);
查看
<%= Html.DropDownList("CategoryID") %>
如果我想要一个默认选项
or if I want a default selection
<%= Html.DropDownList("CategoryID",
(IEnumerable<SelectListItem>)ViewData["CategoryID"],
"Select a Category" ) %>
修改
有关下拉列表中的有趣的一点是,你需要提供一系列从数值来选择适合你的实际的数据模型的单一值。我通常提供通过查看数据的范围(菜单项),并在页面张贴期待后面的模型值。如果你想强类型的菜单,以及,你需要提供你的封装了真正的模型和任何菜单仅查看模式。这将涉及上张贴,使用prefixes的识别模型元素。权衡,在我看来,就是简单的模型与视图中使用强类型的菜单上后绑定。我不挂了后者,所以我选择不把我的菜单,在模型中。如果你想这样做,但是,它可能看起来像下面这样。
The interesting bit about the dropdown list is that you need to supply a range of values from which to select a single value that fits into your actual data model. I typically provide the range (menu items) via view data and expect back the model values when the page is posted. If you wanted strongly-typed menus as well, you'd need to provide a view-only model that encapulates your real model and any menus. This would involve, on posting, the use of prefixes to identify the model elements. The trade-off, to my mind, is simpler model binding on post vs. the use of strongly-typed menus in the view. I'm not hung up on the latter, so I opt not to put my menus in the model. If you wanted to do this, though, it might look like the following.
型号
public class CategoryViewModel
{
public Category Category { get; set; }
public IEnumerable<SelectListItem> CategoryMenu { get; set; }
...
}
控制器
的显示动作的
var model = new CategoryViewModel();
model.CategoryMenu = categories.Select( c => new SelectListItem
{
Text = c.CategoryName,
Value = c.CategoryID
}
);
...
return View(model);
的创建行动的
[AcceptVerbs( HttpVerbs.Post )]
public ActionResult Create( [Bind(Prefix="Category")]Category category )
{
...
}
查看
<%= Html.TextBox("Category.Name") %>
<%= Html.DropDownList("Category.CategoryID",
Model.CategoryMenu,
"Select a Category" ) %>
这篇关于ASP.NET MVC的DropDownList的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!