MVC Jquery 转到控制器动作
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8332755/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
MVC Jquery go to controller action
提问by Nate Pet
In Jquery, I need to tell the program to go to EmployeeController and Empl action. How do I tell it do this. I want to simple way to do this without using ajax.
在 Jquery 中,我需要告诉程序转到 EmployeeController 和 Empl 操作。我怎么告诉它这样做。我想在不使用ajax的情况下使用简单的方法来做到这一点。
回答by Adam Terlson
window.location.href = "/{controller}/{action}" //in your case, /employee/empl
This works because of the routes specified in your Global.asax.cs file. I suggest you read up on how this works as it's one of the fundamentals of MVC....
这是因为 Global.asax.cs 文件中指定的路由。我建议你阅读它是如何工作的,因为它是 MVC 的基础之一......
回答by BigMike
Well, all good response so far, but using a magic string for building url just gives me the chills. I prefer to add an extension like this:
好吧,到目前为止所有的反应都很好,但是使用魔术字符串来构建 url 只会让我不寒而栗。我更喜欢添加这样的扩展:
public static string GetUrl(this HtmlHelper, helper, string Action, string Controller, object RouteValues)
{
UrlHelper Url = new UrlHelper(HttpContext.Current.Request.RequestContext);
return Url.Action(Action, Controller, RouteValues);
}
and then in my js code use:
然后在我的 js 代码中使用:
location.href = '@Html.GetUrl("Action", "Controller", new { foo=Model.Foo })';
It's more consistent, internally cares about routing, and gives me a centralized point where doing nasty things on Urls :)
它更一致,内部关心路由,并为我提供了一个集中点,可以在 Urls 上做讨厌的事情:)
Well, one more thing,
嗯,还有一件事,
window.location = "whatever";
is good and works, still
很好,有效,仍然
location.href = "whatever";
is preferreable.
是优选的。
HTH
HTH
回答by Mir Gulam Sarwar
Accepted answer doesn't work when the application is Published. I had to use
当应用程序发布时,接受的答案不起作用。我不得不使用
window.location.href='@Url.Action("ActionName","ControllerName")'
Hope it helps
希望能帮助到你
回答by Mostafa Elzaref
and for parameters
和参数
window.location.href = "/{controller}/{action}?parm1=val1&parm2=val2"
回答by simshaun
Making assumptions about the URI structure & routing, but:
对 URI 结构和路由做出假设,但是:
window.location = '/employee/empl/';
window.location = '/employee/empl/';