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 :
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;
}
@Shimmy is there a way to do this as a one-liner, without defining the function in js?
yes you can and here is the code for that:
@Html.DropDownListFor(m => m.Name, new SelectList((System.Collections.IEnumerable)ViewBag.DropDownName, "Value", "Text"), new { @class = "form-control", onchange = "document.location.href = '/Home/Employee?c=' + this.options[this.selectedIndex].value;" })
This is a jQuery thing. Give it a class and wire up to it.
Html.DropDownList("ddl", AvailableList, new { @class = "_select_change" })
A rough script might look like this:
$('._select_change').change(function() { $.post(ctrlUrl); })
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 both : D
I propose a mix -I like a lot the jQuery.
$('ddl').change(
function() {
// This contains your selected option val
$(this).val();
// so you can do domething like...
$.post(
$(this).val(),
{ Param1: xxxx,
Param2: xxxx,
Param3: xxxx },
function(data) {
// handle your call here. 'data' contains the response
} );
}
@Html.DropDownListFor(model => model.StudentId, new SelectList(ViewBag.List, "Value", "Text"), new { @class = "form-control", @style = "width:65px", onchange = "document.location.href = '/Student/find?Id=' + this.options[this.selectedIndex].value;" })