Auto Postback with Javascript in ASP.NET MVC

I've looked this up twice now so I'm posting it to my blog for future reference and as a quick-tip for others. Say you got a web page with a dropdown/select listbox and you want to reload/auto postback the page when the selection changes.


One way to do this without involving a Javascript or Ajax library like jQuery (which probably is a good idea anyway :) is to use the "htmlAttributes" parameter of the Html.DropDownList() helper method and add a "onchange" attribute through an anonymous type. Something like this:

    Select a name: <%=Html.DropDownList("Name", ViewData.Model, 
new { onchange = "doSomeJavascript()" })%>

To submit a form, for example:

    <% using (Html.Form<HomeController>(p => p.DropDown(), 
FormMethod.Post, new { id = "myform" })) {%> Select a name: <%=Html.DropDownList("Name", ViewData.Model,
new { onchange = "document.getElementById('myform').submit()" })%> <% } %>


The minimal DropDown() method of the HomeController class to support this sample looks like this:

public object DropDown()
    var list = new List<string> { "Adam", "Bob", "Charlie" };
    return View(new SelectList(list, Request["Name"] ?? list.First()));

As you can see, the htmlAttributes parameter is available on many of the Html-helper methods and I'm using ot to add a name attribute to the HTML form as well.

End Note About Basic Knowledge of Javascript and Html

Heh, ASP.NET MVC sure forces you to dust off that old, basic knowledge of HTML and Javascript that I think every web developer should have but the ASP.NET programming model has made us forgot... One could argue that it's niggy gritty stuff that we shouldn't have to worry about, but for me it feels good to know I'm in full control of the generated HTML and I'm not sending one byte more on the wire than what's needed. Yes, it's possible to have the same control with standard ASP.NET applications and controls, but I've seen experienced developers make mistakes around this more than once. ViewState anyone? :D


Comments have been disabled for this content.