Invoking particular action on dropdown list selection in MVC

Jaqen H'ghar picture Jaqen H'ghar · Feb 6, 2010 · Viewed 85.6k times · Source

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?

Answer

Darin Dimitrov picture Darin Dimitrov · Feb 6, 2010

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;
}