7

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 Answers 4

9

Now that the HtmlHelper extension takes an IEnumerable<SelectListItem>, 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<SelectListItem>)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<SelectListItem> 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" ) %>
Sign up to request clarification or add additional context in comments.

1 Comment

Thats great. Could you provide an example using this with the ViewModel pattern. Thanks
5

Here's one great article by Rob Connery

Controller Code

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

View Markup

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

1 Comment

You don't need the second argument in the html helper. The method will look that up for you if you just pass the "CategoryID".
0

If you need to add html attributes to your tags this would be a way of doing it. Pass a Model to your View e.i. "return View(someModel)" then in the View:

        <select id="Groups" name="Groups">
            <% foreach (SelectListItem item in Model.GroupsDropDown)
               {
                   if (item.Selected)
                   {%>
                        <option selected="selected" title="<%= item.Text %>">
                            <%= item.Text%></option>
                    <%}
                     else
                    {%>
                        <option title="<%= item.Text %>">
                            <%= item.Text%></option>
                    <%} %>
            <% } %>
        </select>

GroupsDropDown is a property in your Model like this:

public IEnumerable GroupsDropDown { get; set; }

Comments

0

Write in the view:

@{
TaskManagerContext context = new TaskManagerContext();

IEnumerable<TestTask1.Models.User> CDrop = context.Users.ToList();
List<SelectListItem> selectList = new List<SelectListItem>();
foreach (var c in CDrop)
{
    SelectListItem i = new SelectListItem();
    i.Text = c.Username.ToString();
    i.Value = c.ID.ToString();
    selectList.Add(i);
}

}

You can reference it ike that:

@Html.DropDownListFor(m => m.UserID,
                          new SelectList(selectList, "Value", "Text"));

You can also choose a specific row:

TaskManagerContext context = new TaskManagerContext();
UsersRepository repo = new UsersRepository();
User user = repo.GetAll().FirstOrDefault(u => u.ID == ViewBag.UserId);
ViewBag.User = user;

<div><h3><label>@ViewBag.Title1</label>@ViewBag.User.Username</h3></div>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.