生成在JavaScript中的操作URL的ASP.NET MVC [英] Generating an action URL in JavaScript for ASP.NET MVC
问题描述
我想通过调用控制器特定参数的操作重定向到另一个页面。我试图用这个行:
I'm trying to redirect to another page by calling an action in controller with a specific parameter. I'm trying to use this line:
window.open('<%= Url.Action("Report", "Survey",
new { id = ' + selectedRow + ' } ) %>');
但我无法使它工作;它提供了以下错误:
But I couldn't make it work; it gives the following error:
CS1012:字符字符太多文字
我能不能产生作用的URL,这是在客户端?还是我通过提供的参数进行Ajax调用并取回所需的网址是什么?这似乎并不正确,但我想,如果它是唯一的方法。
Can't I generate the action URL this was on the client side? Or do I have to make an Ajax call by supplying the parameter and get back the needed URL? This doesn't seem right, but I want to if it's the only way.
有没有更简单的解决方案?
Is there an easier solution?
推荐答案
记住之间&LT一切;%和%>是PTED为C#code间$ P $,所以你实际上做的是试图评价C#以下行:
Remember that everything between <% and %> is interpreted as C# code, so what you're actually doing is trying to evaluate the following line of C#:
Url.Action("Report", "Survey", new { id = ' + selectedRow + ' } )
C#认为单引号周围字符文字,因此,该错误信息你得到(字符文字只能包含在C#中的单个字符)
C# thinks the single-quotes are surrounding a character literal, hence the error message you're getting (character literals can only contain a single character in C#)
也许你曾经可以在页面脚本生成URL - 在你的页面头部的地方,这样做:
Perhaps you could generate the URL once in your page script - somewhere in your page HEAD, do this:
var actionUrl =
'<%= Url.Action("Report", "Survey", new { id = "PLACEHOLDER" } ) %>';
这会给你包含你所需要的URL一个JavaScript字符串,而是用占位符,而不是数量。然后设置你的点击处理程序为:
That'll give you a Javascript string containing the URL you need, but with PLACEHOLDER instead of the number. Then set up your click handlers as:
window.open(actionUrl.replace('PLACEHOLDER', selectedRow));
即。处理程序运行时,你会发现在你的pre-计算URL占位符值,并与选定行更换。
i.e. when the handler runs, you find the PLACEHOLDER value in your pre-calculated URL, and replace it with the selected row.
这篇关于生成在JavaScript中的操作URL的ASP.NET MVC的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!