ASP.NET MVC UrlHelper.Action() 未返回正确的路径
我在尝试使用 UrlHelper
Action()
方法指向我网站上的 /Home/Index
操作时遇到问题。我需要在客户端脚本中动态生成指向 Index
的链接(包括 id
参数),所以我做了显而易见的事情:
var url = '@this.Url.Action("Index", "Home")';
function generateLink ( id ) {
var anchor = "<a href='" + url + "/" + id + "'>Select Me</a>"
return anchor;
}
但是这里生成的锚标记看起来像这样:
<a href='http://localhost//1013'>Select Me</a>
这显然不会导致正确的操作。我假设 Url.Action()
通过弄清楚 Home
和 Index
是我的默认值的默认值而变得“聪明”路由,因此 http://localhost
和 http://localhost/Home
和 http://localhost/Home/Index
在功能上是相同的,但我需要以某种方式强制它选择完整的 URL 选项。
有没有办法做到这一点,或者我必须自己构建 URL?
编辑:
我没有更改新 MVC3 项目的默认路由:
public static void RegisterRoutes ( RouteCollection routes )
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new
{
controller = "Home",
action = "Index",
id = UrlParameter.Optional
} // Parameter defaults
);
}
答案:
我最终对 @BFree 的答案进行了轻微的修改,只是因为如果我可以使用它,我更喜欢 Html.ActionLink() 而不是 Url.Action :
var anchor = '@this.Html.ActionLink("Select Me", "Index", "Home", new { id = "XXX" }, null)';
function generateLink ( id ) {
return anchor.replace("XXX", id);
}
I'm having a problem trying to use the UrlHelper
Action()
method to point to the /Home/Index
action on my site. I need to generate links to Index
dynamically (including an id
parameter) in client-side script, so I did the obvious:
var url = '@this.Url.Action("Index", "Home")';
function generateLink ( id ) {
var anchor = "<a href='" + url + "/" + id + "'>Select Me</a>"
return anchor;
}
But the anchor tags being generated here look like this:
<a href='http://localhost//1013'>Select Me</a>
which obviously doesn't route to the correct action. I'm assuming that Url.Action()
is being "smart" by figuring out that Home
and Index
are the default values for my default route, so http://localhost
and http://localhost/Home
and http://localhost/Home/Index
are functionally identical, but I need to somehow force it to pick the full URL option.
Is there a way to do this, or am I going to have to build the URL up myself?
EDIT:
I haven't change the routing from the defaults for a new MVC3 project:
public static void RegisterRoutes ( RouteCollection routes )
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new
{
controller = "Home",
action = "Index",
id = UrlParameter.Optional
} // Parameter defaults
);
}
ANSWER:
I finally went with a slight variation of @BFree's answer, just because I prefer Html.ActionLink() to Url.Action if I can use it:
var anchor = '@this.Html.ActionLink("Select Me", "Index", "Home", new { id = "XXX" }, null)';
function generateLink ( id ) {
return anchor.replace("XXX", id);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
一种巧妙的方法是执行以下操作:
One hacky approach is to do something like this:
解决方法可能是:
A workaround could be: