MSMVPS.COM
The Ultimate Destination for Blogs by Current and Former Microsoft Most Valuable Professionals.

Autopostback DropDownList with ASP.NET MVC

PropertiesPaneDidn't you love the days back when you could just open up the properties tab for your DropDownList in ASP.NET and set the AutoPostBack Property to True? You could even write code in your codebehind class to handle the event properly. Cool, right? Hot

But these are the days of the ASP.NET MVC framework, so everything's different now. Well, of course I'm being a bit sarcastic Sarcastic here and there are a lot of advantages too to the MVC Framework, but still it requires more work to achieve things-that-used-to-be-simple.

Anyway, back to the AutoPostBack of the DropDownList. First, of course, you need to have a DropDownList on your page:

<select id='dropDown' name='dropDown'>
<option value="1" selected="selected">Option 1</option>
<option value="2">Option 2</option>
</select>

Note that this control needs to be within your Form otherwise it's values will not be submitted of course...

When you have the control, you'll need to make it submit the Form it's in. I chose to do so with jQuery, but you could do it with plain javascript too:

<script type='text/javascript'\> 
  $('#dropDown').change(function () {
$(this).parents('form').submit();
});
</script>

For those of you not fully up to speed with jQuery: this code finds the element named "dropDown" and adds a handler to the onChange event of it. The handler first finds the parent of the DropDownList with elementname "form", and submits it.

You could also change the action of the form here in the handler if that might be needed, for example to fire a specific controller action for the postback of the DropDownList.


Posted Mon, Mar 2 2009 2:44 by Stefan Kamphuis
Filed under: , ,