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.
You can specify on the onchange event a javascript function and inside that function:
var url = '@Html.Raw(Url.Action("MyAction", "controllerName", new { param1=5, param2=2 }))';
and then:
window.location = url;
Finally the code should be:
@Html.DropDownList(
    "viewDataItem", Model.MyEnumerableList as SelectList, 
    new { onchange = "SelectionChanged()" 
    } )
<script>
 function SelectionChanged()
 {
  var url = '@Html.Raw(Url.Action("MyAction", "controllerName", new { param1=5, param2=2 }))';
  window.location = url;
 }
</script>
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With