创建锚标记时,无法正确构建URL.Action链接

时间:2018-02-26 16:43:53

标签: javascript asp.net-mvc url.action

我正在视图中使用function showDetails(data) { var link = "@Url.Action("Index", "Detail")" + "/" + data; var returnText = "<a target='_blank' href='" + link + "'>" + data + "</a>"; return returnText; } 构建锚链接。 构建时,它不包含控制器方法:

console.log(link)

在控制台中显示链接:/Detail/123时,它会向我/Detail/Index/123而不是RouteConfig.cs

这是在 routes.MapRoute( name: "Default", url: "{controller}/{action}/{id}", defaults: new { controller = "Login", action = "Index", id = UrlParameter.Optional } );

中定义路由的方式
Default

我根据您的建议 routes.MapRoute( name: "TicketDetail", url: "Detail/Index/{data}", defaults: new {controller = "Detail", action = "Index", data =UrlParameter.Optional } ); 路线

添加了以下内容
get_color

我错过了什么?

1 个答案:

答案 0 :(得分:0)

Well you have a combination of problems. First

it gives me /Detail/123 instead of /Detail/Index/123

Because Index is the default route so /Detail is actually 100% correct.

//                                            Default = Index
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
    );

There is no reason to add Index to the URL as Asp.Net sees it. It does add Detail because Detail != Home. If you changed the default to Detail it would give you just /. If you want to force the url you can create your own helper (from the duplicate question/answer).

public static string AbsoluteAction(this UrlHelper url,
  string actionName, string controllerName, object routeValues = null)
{
  string scheme = url.RequestContext.HttpContext.Request.Url.Scheme;

  return url.Action(actionName, controllerName, routeValues, scheme);
}

You can then simply use it like that in your view:

@Url.AbsoluteAction("Action", "Controller")

Secondly, because you are adding data on the client side as a path parameter instead of query parameter it doesn't work. You could keep your code exactly as is if you did:

var link = "@Url.Action("Index", "Detail")" + "?id=" + data;      

or

var link = "@Url.Action("Index", "Detail")" + "?data=" + data;      

not sure what your method is expecting because you didn't include it in the relevant code.