MVC3 - Javascript 中的动态 URL 重定向
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7352560/
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
MVC3 - Dynamic URL redirect in Javascript
提问by Anthony Queen
I am using C#, MVC3, and Razor.
我正在使用 C#、MVC3 和 Razor。
I have a javascript function (in the view) that gets called when a particular menu item is clicked. In this function, I need to build a new URL with parameters (based on other selections on the screen) and redirect to it. It want it to do something like this:
我有一个 javascript 函数(在视图中),当单击特定菜单项时会调用该函数。在这个函数中,我需要构建一个带有参数的新 URL(基于屏幕上的其他选择)并重定向到它。它希望它做这样的事情:
ValueA and ValueB are variables in the javascript section and are populated with values.
ValueA 和 ValueB 是 javascript 部分中的变量,并填充了值。
function doSomething(ID) {
location.href = "../Area/Controller/Action?ID=" + ID + "&ValueA=" + ValueA + "&ValueB=" + ValueB;
}
However, due to the nature of MVC I need to make sure the URL is always right, regardless of how the user got to the page. I've tried to use @Url.Content("") (see next code block) but the issue I run into is:
但是,由于 MVC 的性质,我需要确保 URL 始终正确,无论用户如何到达页面。我尝试使用 @Url.Content("") (请参阅下一个代码块)但我遇到的问题是:
- The name 'ID' does not exist in the current context
- The name 'ValueA' does not exist in the current context
- The name 'ValueB' does not exist in the current context
- 当前上下文中不存在名称“ID”
- 当前上下文中不存在名称“ValueA”
- 当前上下文中不存在名称“ValueB”
Here is an example of what I would like to do but get the above mentioned errors on:
这是我想做的一个示例,但会出现上述错误:
function doSomething(ID) {
location.href = @Url.Content("~/Area/Controller/Action?ID=" + ID + "&ValueA=" + ValueA + "&ValueB=" + ValueB);
}
How can I make this work? Is there a better way?
我怎样才能使这项工作?有没有更好的办法?
Thanks, Tony
谢谢,托尼
回答by SLaks
You should concatenate the the static part to the dynamic part:
您应该将静态部分连接到动态部分:
location = "@Url.Content("~/Area/Controller/Action")?ID=" + ID + "&ValueA=" + ValueA + "&ValueB=" + ValueB;
The outer "@...?ID="
is a Javascript string literal.@Url.Content("...")
is server-side code that emits raw text into the Javascript literal.
外部"@...?ID="
是一个 Javascript 字符串文字。@Url.Content("...")
是将原始文本发送到 Javascript 文字的服务器端代码。