DropDownList选项更改时,使用参数重定向到MVC ActionResult

我正在使用MVC创建网站的一部分。 在我的一个视图中,我有一个DropDownList 。 当选择一个新的下拉列表选项,或者换句话说onchange ,我希望我的页面被重定向到特定的Controller ActionResult 。 如果没有参数,我可以访问MyAction ActionResult但是我无法弄清楚如何发送所需的参数。

我的控制器动作:

 public virtual ActionResult MyAction(int param1, int param2) { return View(); } 

我在视图中的DropDownList:

 @Html.DropDownList( "viewDataItem", Model.MyEnumerableList as SelectList, new { onchange = @" var form = document.forms[0]; form.action='MyAction'; form.submit();" } ) 

上面的代码调用MyAction,但它不发送参数。 有没有办法以某种方式将参数添加到此代码?

另一个想法是以某种方式使用@{Response.Redirect(@Url.Action("MyAction", "myController", new { param1 = 2, param2= 3 }));}作为我的DropDownList操作,因为Response.Redirect允许我使用参数重定向到MyAction。 有没有办法以某种方式使onchanged = Response.Redirect?

尝试使用onchange等同于响应,但是当我更改选项时没有任何反应:

 @Html.DropDownList( "name", Model.MyEnumerableList as SelectList, new { onchange = {Response.Redirect(@Url.Action("MyAction", "controllerName", new { param1 = 5, param2 = 3 }));} }) 

简而言之,每当我的DropDownList选项被更改时,如何使用参数调用ActionResult?

在这里和这里都提出了类似的问题,但这些链接中提供的答案都使用JavaScript,我不知道如何使用JS和cshtml。 我尝试了一些答案,但没有一个能解决我的问题。

您可以在onchange事件上指定一个javascript函数并在该函数内部:

 var url = '@Html.Raw(Url.Action("MyAction", "controllerName", new { param1=5, param2=2 }))'; 

然后:

 window.location = url; 

最后代码应该是:

 @Html.DropDownList( "viewDataItem", Model.MyEnumerableList as SelectList, new { onchange = "SelectionChanged()" } )  

有没有办法以某种方式将参数添加到此代码?

当然,有很多方法。 其中之一是:

 @Html.DropDownList( "viewDataItem", Model.MyEnumerableList as SelectList, new { onchange = @" var form = document.forms[0]; form.action='MyAction?param1=5&param2=3'; form.submit(); /*Just make sure that form 'method' attribute is set to 'post'*/" } ) 

但是你提到的答案中描述了一种更好的方法。

有没有办法以某种方式使onchanged = Response.Redirect?

不是你尝试使用它的方式。 onchanged是一个javascript事件,javascript对Response属性或其他MVC服务器端的东西一无所知。