ASP.NET MVC dropdownlist

后端 未结 4 1071
后悔当初
后悔当初 2021-02-06 09:35

Can someone point me to an article that shows the dropdownlist being populated from linq to sql (text and value being set).

Thanks Danny

4条回答
  •  星月不相逢
    2021-02-06 10:14

    Now that the HtmlHelper extension takes an IEnumerable, I don't create SelectList's, but usually just create the SelectListItems with LINQ.

    Controller

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

    View

    <%= Html.DropDownList("CategoryID") %>
    

    or if I want a default selection

    <%= Html.DropDownList("CategoryID",
                          (IEnumerable)ViewData["CategoryID"],
                          "Select a Category" ) %>
    

    EDIT:

    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.

    Model

    public class CategoryViewModel
    {
        public Category Category { get; set; }
        public IEnumerable CategoryMenu { get; set; }
        ...
    }
    

    Controller

    Display action

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

    Create action

    [AcceptVerbs( HttpVerbs.Post )]
    public ActionResult Create( [Bind(Prefix="Category")]Category category )
    {
       ...
    }
    

    View

    <%= Html.TextBox("Category.Name") %>
    
    <%= Html.DropDownList("Category.CategoryID",
                          Model.CategoryMenu,
                          "Select a Category" ) %>
    

提交回复
热议问题