ASP.NET MVC DropdownList PostBack

by KodefuGuru 29. November 2009 16:41

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.

Tags: , , , ,

Kodefu

Comments

11/29/2009 4:46:06 PM #

trackback

Trackback from DotNetKicks.com

ASP.NET MVC DropdownList PostBack

DotNetKicks.com

11/29/2009 11:21:24 PM #

trackback

Trackback from WebDevVote.com

ASP.NET MVC DropdownList PostBack

WebDevVote.com

12/4/2009 8:51:03 AM #

Steve

Alternatively you can load a partial view with ajax

Steve

12/5/2009 6:18:47 PM #

SuperDude

I've tried this code, but the blogName appears as null when the JsonResult is called...any ideas?

SuperDude United Kingdom

12/5/2009 7:04:27 PM #

chris

SuperDude: Did you remember to put the route in global.asax? I named the parameter on the action, so it needs the route. Otherwise, you could name it "id" and use the default route.

chris United States

2/20/2010 5:37:23 PM #

Altaf Khatri

ASP.NET MVC dropdownlist postback using the server side code can be found at:

www.altafkhatri.com/.../PostBack

Altaf Khatri United States

2/26/2010 12:29:23 PM #

Karl

Reading nice blogs enable me to connect to other people and learn something new about their experiences.  Thanks for posting this.

Karl Republic of the Philippines

Add comment




  Country flag

biuquote
  • Comment
  • Preview
Loading



Powered by BlogEngine.NET 1.6.0.0
Theme by Mads Kristensen

Whois KodefuGuru

Chris Eargle

Chris Eargle
.NET Community Champion

LinkedIn Twitter Technorati Facebook

MVP - Visual C#

 

INETA Community Champions
Friend of RedGate
Telerik .NET Ninja
Community blogs & blog posts

I am a #52er


World Map

RecentComments

Comment RSS

Tag cloud

Disclaimer

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

© Copyright 2010