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¶m2=3'; form.submit(); /*Just make sure that form 'method' attribute is set to 'post'*/" } )
但是你提到的答案中描述了一种更好的方法。
有没有办法以某种方式使onchanged = Response.Redirect?
不是你尝试使用它的方式。 onchanged
是一个javascript事件,javascript对Response
属性或其他MVC服务器端的东西一无所知。
上述就是C#学习教程:DropDownList选项更改时,使用参数重定向到MVC ActionResult分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!
本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。
ctvol管理联系方式QQ:251552304
本文章地址:https://www.ctvol.com/cdevelopment/954639.html