Monday, January 10, 2011

ASP.Net MVC - How to postback to the server when a dropdown changes


I recently needed to call a controller action on the server when a dropdown list on a web page changed. This is a fairly common scenario and in this case I was needing to show a list of options from the database based on the value of the dropdown. If the dropdown was contained within a form element I could have called the form submit method and posted back that way, but it wasn't so I had to come up with another way.


We can trigger the web page to call back to the desired controller and action on the server by using some javascript to assign the desired URL to the window.location.href property of the page.

<script type="text/javascript">
  function ChangeLanguage() {
    window.location.href = <%= String.Format("'{0}'",
      Url.Content("~/FileUpload/Index/")) %> + $('#language').val();

I've used some jQuery goodness here to grab the selected value of the dropdown list by using the val() method. This is then appended to the URL of the controller action and can be accessed by declaring the method on the server with an id parameter:

public ActionResult Index(int? id)
  //do something with the id

Now all we need to do is hook up the ChangeLanguage() function to the language dropdown list:

<%: Html.DropDownList("language", (SelectList)ViewData["LanguageList"],
            new { onchange = "ChangeLanguage(); return false;" })%>

This could have been done using jQuery to bind to the dropdown list change event but for this simple page I didn't see the need.

Posting back to the server when a dropdown list changes - done!

No comments:

Post a Comment