Bookmark and Share

ASP.NET MVC DropDownList PostBack Follow-up

In 2009, I wrote how to do “postbacks” with the ASP.NET MVC DropDownList control. I wrote the post in response to questions in the forums, and lately that particular article has had a lot of traffic. Now, I don’t explain how to do true postbacks, only how to achieve the same effect. What you really do is use jQuery to retrieve the information. It’s a much more elegant solution.

This follow-up is necessary because I wrote that article for ASP.NET MVC 1. The code doesn’t work for the later versions, as is evidences by a few comments on that article. Fixing it is a simple matter of adding a parameter to the Controller Action.

public JsonResult Owner(string blogName)
{
    return Json(BlogOwner.Create(blogName), JsonRequestBehavior.AllowGet);
}

While I was looking over this example, I decided another change was warranted. I had hard-coded the blog names in the view. No matter where they come from, this is a bad idea. I moved the blog names to the ViewBag.BlogNames property, and pieced together the items in a variable. Since I switched the view over to Razor, it’s somewhat different now. Here is the resulting View code (sans the JavaScript since it is the same).

@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";
    var listItems = new List<SelectListItem>();
    listItems.Add(new SelectListItem{Text = String.Empty, Value = String.Empty});
    foreach(string name in ViewBag.BlogNames)
    {
        listItems.Add(new SelectListItem { Text = name, Value = name });
    }
}

<h2>Index</h2>
@Html.DropDownList("dropDownList", listItems)
<h2>Owner</h2>
<p>
    <span>First Name</span><br />
    @Html.TextBox("firstName")
</p>
<p>
    <span>Last Name</span><br />
    @Html.TextBox("lastName")
</p>

The Controller is responsible for retrieving the blog names (typically by calling other components) and assigning them to the ViewBag.BlogNames property, as controllers are responsible for compositional logic for the model and view. However, the view is responsible for taking the composed data and constructing visual elements from it.

Download the source from my SkyDrive.

blog comments powered by Disqus

KodefuGuru.GetInfo()

Chris Eargle
LinkedIn Twitter Technorati Facebook

Chris Eargle
Telerik Developer Evangelist, C# MVP

JustCode

Telerik .NET Ninja

 

INETA Community Speakers Program

 

MVP - Visual C#

 

Friend of RedGate

World Map

Month List

Disclaimer

The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.

© Copyright 2010
Disclaimer: The opinions expressed herein are my own personal opinions and do not represent my employer’s view in any way.