Using Url.Action in javascript

独自空忆成欢 提交于 2020-01-11 04:23:04

问题


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:

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.

Is there a way using razor syntax which will allow this code to compile?


回答1:


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.

PS: I am assuming you are using the Default Route Tables.




回答2:


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)); 


来源:https://stackoverflow.com/questions/17701510/using-url-action-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!