ASP.NET MVC下拉列表

Dan*_*nny 7 asp.net-mvc

有人能指出我的文章,显示从linq到sql(正在设置的文本和值)填充的下拉列表.

谢谢丹尼

tva*_*son 9

既然HtmlHelper扩展需要一个IEnumerable<SelectListItem>,我不创建SelectList,但通常只用LINQ创建SelectListItems.

调节器

ViewData["CategoryID"] = categories.Select( c => new SelectListItem
                                                 {
                                                     Text = c.CategoryName,
                                                     Value = c.CategoryID
                                                 }
                                          );
Run Code Online (Sandbox Code Playgroud)

视图

<%= Html.DropDownList("CategoryID") %>
Run Code Online (Sandbox Code Playgroud)

或者如果我想要默认选择

<%= Html.DropDownList("CategoryID",
                      (IEnumerable<SelectListItem>)ViewData["CategoryID"],
                      "Select a Category" ) %>
Run Code Online (Sandbox Code Playgroud)

编辑:

下拉列表中有趣的一点是,您需要提供一系列值,从中选择适合您实际数据模型的单个值.我通常通过视图数据提供范围(菜单项),并期望在发布页面时返回模型值.如果您还需要强类型菜单,则需要提供一个仅包含视图的模型来封装您的实际模型和任何菜单.这将涉及在发布时使用前缀来标识模型元素.在我看来,权衡是对帖子的简单模型绑定与在视图中使用强类型菜单.我没有挂在后者上,所以我选择不把我的菜单放在模型中.但是,如果你想这样做,它可能如下所示.

模型

public class CategoryViewModel
{
    public Category Category { get; set; }
    public IEnumerable<SelectListItem> CategoryMenu { get; set; }
    ...
}
Run Code Online (Sandbox Code Playgroud)

调节器

显示动作

var model = new CategoryViewModel();
model.CategoryMenu = categories.Select( c => new SelectListItem
                                                 {
                                                     Text = c.CategoryName,
                                                     Value = c.CategoryID
                                                 }
                                      );

...
return View(model);
Run Code Online (Sandbox Code Playgroud)

创建行动

[AcceptVerbs( HttpVerbs.Post )]
public ActionResult Create( [Bind(Prefix="Category")]Category category )
{
   ...
}
Run Code Online (Sandbox Code Playgroud)

视图

<%= Html.TextBox("Category.Name") %>

<%= Html.DropDownList("Category.CategoryID",
                      Model.CategoryMenu,
                      "Select a Category" ) %>
Run Code Online (Sandbox Code Playgroud)


Jos*_*lio 5

这是Rob Connery撰写的一篇精彩文章

控制器代码

NorthwindDataContext db = new NorthwindDataContext();
var categories = from c in db.Categories select c;
ViewData["CategoryID"] = new SelectList(categories, "CategoryID", "CategoryName");
Run Code Online (Sandbox Code Playgroud)

查看标记

<%=Html.DropDownList("CategoryID")%>
Run Code Online (Sandbox Code Playgroud)