Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Invoking particular action on dropdown list selection in MVC

Tags:

I have a dropdown list in an MVC view. On selection change of dropdown list I want to call specific action method in the controller.

What I have done on view is this :

<%=Html.DropDownList("ddl", ViewData["AvailableList"] as SelectList,   new { onchange = "this.form.action='MyMethod';this.form.submit();" })%> 

Everything is getting compiled. But a runtime exception is thrown when I change the drop down selection, as

"Microsift JScript Runtime Error : Object doesn't support property or method"

How can I redirect to specific action on list selection change event?
How can I pass parameters to this action method?

like image 496
Jaqen H'ghar Avatar asked Feb 06 '10 12:02

Jaqen H'ghar


2 Answers

Do you really need to submit the form? You could redirect:

onchange = "redirect(this.value)" 

where redirect is a custom defined function:

function redirect(dropDownValue) {     window.location.href = '/myController/myAction/' + dropDownValue; } 
like image 175
Darin Dimitrov Avatar answered Oct 01 '22 09:10

Darin Dimitrov


Your approach should work. The issue you're encountering is your use of this in your onchange event is invalid. Try replacing your this.form references with something like this:

<%= Html.DropDownList(         "ddl", ViewData["AvailableList"] as SelectList,          new { onchange = @"             var form = document.forms[0];              form.action='MyMethod';             form.submit();"          } ) %> 
like image 37
Jacob Avatar answered Oct 01 '22 09:10

Jacob