In this recipe, we are going to look at how to replicate another standard ASP.NET web forms feature. We frequently need to present a drop-down list as a form of navigation. When the user selects an item from the list, we want the form to post itself so that we can do something with the selected value.
Controllers
directory. We're going to create a little helper method to generate a small list of articles.Controllers/HomeController.cs:
private List<Article> GetArticles() {
return new List<Article> {
new Article {
ID = Guid.Parse("f4838485-058d-4c82-b4f4-3bd8c81c7d09"),
Title = "Title 1",
Description = "Description 1" },
new Article {
ID = Guid.Parse("67f19f15-9ba8-4624-91a4-152aec01c5f8"),
Title = "Title 2",
Subject = "This one has a subject.",
Description = "And a description." }
};
}
ViewArticle
. Each of the actions grabs the list of articles and adds the list to a ViewData
dictionary item called ArticleList
. Also, both the actions send an individual articlel
to the view, using differing LINQ methods. Because no selection has been made when the user first loads the ViewArticle
view, the GET
action will return the first of our dummy articles (FirstOrDefault()). When a selection has been made, the POST
action will return the desired article (SingleOrDefault(i => i.ID == article.ID)
).[HttpPost] public ActionResult ViewArticle(Guid id) { var articles = GetArticles(); ViewData["ArticleList"] = articles; return View(articles.SingleOrDefault(i => i.ID == id)); } public ActionResult ViewArticle() { var articles = GetArticles(); ViewData["ArticleList"] = articles; return View(articles.FirstOrDefault()); }
/Home/ViewArticle
, you'd see our first dummy article laid out in a FIELDSET
. But what we want to do is add the ability to select a different article from a drop-down list. Add the following code above the FIELDSET
tag.Views/Home/Article.aspx:
<% using (Html.BeginForm()) {%>
<%= Html.DropDownList("id", new SelectList(ViewData["ArticleList"] as List<Forms.Models.Article>, "ID", "Title"), new { onchange = "this.form.submit();"}) %>
<input type="submit" value="Change" />
<% } %>
Home/Article
should show you the drop-down with the first item asking you to Choose... an item from the list. Choosing an item from the list should cause the form to post itself.In this recipe, we created a simple details page to view our dummy articles. Setting the onchange
event of the drop-down list runs some inline JavaScript that causes the form to submit itself. With this recipe, I want to illustrate how small changes can make a big impact on the user experience.
However, in a real world scenario, I have two concerns with the code in its current state.
nojs)
to the unnecessary Submit buttons. I'll then hide or remove those buttons with JavaScript to keep the UI clean.$(function() { $(".nojs").remove(); });
$("select").change(function () { $(this).parents("form").submit(); });