C# 在 JavaScript 中使用 Url.Action
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17701510/
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
Using Url.Action in javascript
提问by philreed
I am trying to use the Url.Action method to correctly generate the required Url for an ajax call but I'm running into problems when trying to build the RouteValues, here's the problem line of code:
我正在尝试使用 Url.Action 方法为 ajax 调用正确生成所需的 Url,但在尝试构建 RouteValues 时遇到问题,这是问题代码行:
var url = @Url.Action("ViewFile", "Default", new { itemId = $(this).data("itemid") });
As you can see, I'm trying to assign the result of the JQuery $(this).data("itemid")
to itemId
in the RouteValues.
正如你所看到的,我想对jQuery的结果分配$(this).data("itemid")
给itemId
在RouteValues。
Is there a way using razor syntax which will allow this code to compile?
有没有办法使用 razor 语法来编译这段代码?
采纳答案by Felipe Oriani
You are confusing client side with server side. Try something like this:
您将客户端与服务器端混淆了。尝试这样的事情:
var url = '@Url.Action("ViewFile", "Default")?itemId=' + $(this).data("itemid");
when you write a @
with razor view engine, you are writing a instruction that will be process on the server side at the end of this command. In your case you want to add a parameter in the url that comes from the javascript, so, just concat on the client side the value with the url generated by the @Url
helper.
当您@
使用剃刀视图引擎编写一个指令时,您正在编写一条指令,该指令将在此命令结束时在服务器端进行处理。在您的情况下,您想在来自 javascript 的 url 中添加一个参数,因此,只需在客户端将值与@Url
助手生成的 url 连接起来。
PS: I am assuming you are using the Default Route Tables.
PS:我假设您使用的是默认路由表。
回答by VahidN
Another way is to create a place holder and then replace it:
另一种方法是创建一个占位符,然后替换它:
var url = '@Url.Action("GetOrderDetails", "Home", new { id = "js-id" })'
.replace("js-id", encodeURIComponent(rowId));