I am using MVC to create part of a website. In one of my Views I have a DropDownList
. When a new drop down list option is selected, or in other words onchange
, I want my page to be redirected to a specific Controller ActionResult
. I am able to get to MyAction
ActionResult if there are no parameters, however I can't figure out how to send in the needed parameters.
My Controller Action:
public virtual ActionResult MyAction(int param1, int param2)
{
return View();
}
My DropDownList in View:
@Html.DropDownList(
"viewDataItem", Model.MyEnumerableList as SelectList,
new { onchange = @"
var form = document.forms[0];
form.action='MyAction';
form.submit();"
} )
The above code calls MyAction, however it does not send in the parameters. Is there a way to somehow add the parameters to this code?
Another thought was to somehow use @{Response.Redirect(@Url.Action("MyAction", "myController", new { param1 = 2, param2= 3 }));}
as my DropDownList action since Response.Redirect allows me to redirect to MyAction with parameters. Is there a way to somehow make onchanged = Response.Redirect?
The tried making onchange equal the response, but the nothing happens when I change my option:
@Html.DropDownList(
"name", Model.MyEnumerableList as SelectList,
new
{
onchange = {Response.Redirect(@Url.Action("MyAction", "controllerName", new { param1 = 5, param2 = 3 }));}
})
In short, how do I call an ActionResult with parameters whenever my DropDownList option is changed?
Similar questions were asked here and here, but the answers provide in those links all use JavaScript and I don't know how to use JS with cshtml. I tried some of those answers, but none of them solved my problems.
Sure, there are many ways. One of them would be:
But a much better way is described in the answer you mentioned.
Not the way you're trying to use it.
onchanged
is a javascript event, and javascript knows nothing aboutResponse
property or other MVC server-side stuff.You can specify on the onchange event a javascript function and inside that function:
and then:
Finally the code should be: