I came across a post in the asp.net forums where someone asked how to do a postback when someone selected an item in a dropdownlist in ASP.NET MVC.
I would like to know how to Select a value from a dropdown list, so that it does a postback and fills the rest of the form textboxes with data
Whereas you can’t exactly do a postback in MVC, you can still respond to a DropDownList’s change event and fill in the rest of a form from data retrieved from your application.
To set the project up, I opened an empty ASP.MVC 1.0 project. I then modified the Home/Index view to contain the requisite elements.
<h2>Blog</h2>
<%=Html.DropDownList("dropDownList", new[]
{
new SelectListItem { Text="", Value="" },
new SelectListItem { Text = "KodefuGuru", Value = "KodefuGuru" },
new SelectListItem { Text = "PlatinumBay", Value = "PlatinumBay" }
})
%>
<h2>Owner</h2>
<p>
<span>First Name</span><br />
<%=Html.TextBox("firstName") %>
</p>
<p>
<span>Last Name</span><br />
<%=Html.TextBox("lastName") %>
</p>
The dropdownlist contains three SelectListItems: blank, KodefuGuru, and PlatinumBay. The intent is to show the blog owner’s first and last name in the text boxes when the dropDownList’s selection changes. To set this up, we will need to define a new action to return Json data.
Here’s the route in Global.asax.
routes.MapRoute("Owner", "Home/Owner/{blogName}",
new { controller = "Home", action = "Owner", blogName = "" });
Here’s the action in HomeController.cs.
public JsonResult Owner(string blogName)
{
return Json(BlogOwner.Create(blogName));
}
This will instantiate a new BlogOwner and serialize it to Json for consumption by the page. The BlogOwner class and factory method are pretty simple since this is just a proof.
public class BlogOwner
{
public string FirstName { get; set; }
public string LastName { get; set; }
public static BlogOwner Create(string blogName)
{
if (blogName == "KodefuGuru")
{
return new BlogOwner
{
FirstName = "Chris",
LastName = "Eargle"
};
}
if (blogName == "PlatinumBay")
{
return new BlogOwner
{
FirstName = "Steve",
LastName = "Andrews"
};
}
return new BlogOwner();
}
}
Now that everything is handled on the server side, it’s time to plug the code up client side. The great news is… there is no postback! There will be no reloading of the screen or any of that mess, and it is very easy to consume and use the action. Additionally, the action is testable so if someone breaks our screen we can know before a build goes out.
To use the action and consume the Json data, we’re going to use jQuery. This will allow us to easily handle the change event of dropDownList, call the action, then set the fields. Place the code in the Home/Index view.
<script type="text/javascript">
$("#dropDownList").change(function() {
$("#dropDownList option:selected").each(function() {
$.getJSON("/Home/Owner/" + $(this)[0].value, null, function(data) {
$("#firstName")[0].value = data.FirstName;
$("#lastName")[0].value = data.LastName;
});
});
});
</script>
This script handles the change event of the dropDownList element. Then, it goes through each selected option and will call the server with the value of the option (there should really be only one, but this can easily be modified to handle multiselect). After the server is called, json data is returned in the variable data. We then set the corresponding values from the json object to the firstName and lastName elements value. The reason for all of the “[0]” is that jQuery returns arrays of elements by default. In this code example, it is necessary to edit the first one found.
Filling form data from dropdownlists in ASP.NET MVC is easy with jQuery, and it makes for a pleasing user experience.