[英]Why friendly url with ASP.NET MVC5 Routing attributes doesn't work everytime?
I want to know why a friendly URL is generated from one action and not on the other. 我想知道为什么从一个动作而不是另一个动作生成友好的URL。
Let's me show you! 让我告诉你!
[RoutePrefix("fr-ca/guest")]
public class GuestController : BaseController
{
[Route("users/{id:int}/{ids:int}")]
public ActionResult Index(int id, int ids)
{
return View();
}
[Route("register/{id:int}/{ids:int}")]
public ActionResult Register(int id, int ids)
{
return View();
}
}
To get the friendly URL results, I use Razor like this: 为了获得友好的URL结果,我使用Razor像这样:
@Html.ActionLink("some text", "Index", "Guest", new { id = 1, ids = 1 }, null)
@Html.ActionLink("some other text", "Register", "Guest", new { id = 1, ids = 1 }, null)
And in the route config file I added this line: routes.MapMvcAttributeRoutes();
在路由配置文件中,我添加了以下行:
routes.MapMvcAttributeRoutes();
So the first on work properly, I get the http:.../fr-ca/guest/users/1/1 But the second one doesn't work! 因此,第一个正常工作,我得到了http:... / fr-ca / guest / users / 1/1,但是第二个无效! I get http:.../fr-ca/guest/register?id=1&ids=1
我得到http:... / fr-ca / guest / register?id = 1&ids = 1
Anyone can help? 有人可以帮忙吗?
Thank you!! 谢谢!!
David 大卫
Assuming you do not have any other route definition which is conflicting with this, 假设您没有与此冲突的其他路线定义,
@Html.ActionLink("some other text", "Register", "Guest", new { id = 1, ids = 1 }, null)
will generate anchor tag with href value as http://yoursitename/fr-ca/guest/register/1/1
, not http:.../fr-ca/guest/register?id=1&ids=1
@Html.ActionLink("some other text", "Register", "Guest", new { id = 1, ids = 1 }, null)
将生成带有href值的锚标记,其值为http://yoursitename/fr-ca/guest/register/1/1
,不是http:.../fr-ca/guest/register?id=1&ids=1
Since you have specified the pattern as register/{id:int}/{ids:int}
It should work fine for register/1/1
url, but not for /register?id=1&ids=2
. 由于您已将模式指定为
register/{id:int}/{ids:int}
因此它对于register/1/1
url应该可以正常工作,但对于/register?id=1&ids=2
无效。 That is the expected behavior. 那是预期的行为。
Instead of using Html.ActionLink
you can use Html.RouteLink
. 可以使用
Html.RouteLink
代替使用Html.ActionLink
。 This helper has an overload that takes the name of a route to be used. 该帮助程序有一个重载,该重载使用要使用的路由的名称。 You must add a name to your route though:
您必须通过以下方式为路线添加名称:
In your controller: 在您的控制器中:
[Route("register/{id:int}/{ids:int}", Name="GuestRegister")]
public ActionResult Register(int id, int ids)
{
return View();
}
In your view: 您认为:
@Html.RouteLink("some other text", "GuestRegister", new { id = 1, ids = 1 }, null)
This results in: 结果是:
http://.../fr-ca/guest/register/1/1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.