Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redirect to MVC ActionResult with Parameters when DropDownList option is changed

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.

like image 357
Tot Zam Avatar asked Jan 09 '23 02:01

Tot Zam


1 Answers

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>
like image 95
Arnel Avatar answered Jan 19 '23 22:01

Arnel