Asp.net mvc Asp.NETMVC4路由和链接生成
在ASP.NETMVC4中,我想知道链接是如何为我生成的 假设一个简单的控制器有3个动作,每个动作都有一个整数参数“requestId”,例如:Asp.net mvc Asp.NETMVC4路由和链接生成,asp.net-mvc,url,parameters,include,routes,Asp.net Mvc,Url,Parameters,Include,Routes,在ASP.NETMVC4中,我想知道链接是如何为我生成的 假设一个简单的控制器有3个动作,每个动作都有一个整数参数“requestId”,例如: public class HomeController : Controller { public ActionResult Index(int requestId) { return View(); } public ActionResult About(int requestId) {
public class HomeController : Controller
{
public ActionResult Index(int requestId)
{
return View();
}
public ActionResult About(int requestId)
{
return View();
}
public ActionResult Contact(int requestId)
{
return View();
}
}
和此注册路由(在默认路由之前):
我使用http://localhost:123/home/index/8
在该视图中,我呈现其他两个操作的链接:
@Html.ActionLink("LinkText1", "About")
@Html.ActionLink("LinkText2", "Contact")
现在,我希望MVC呈现这些链接,包括“requestId”的当前路由值,如下所示:
http://localhost:123/home/about/8
http://localhost:123/home/contact/8
但是我得到了这些链接(没有参数):
…但如果我要指定一个,则不是索引操作:
@Html.ActionLink("LinkText3", "Index")
我要避免的是以这种方式显式指定参数:
@Html.ActionLink("LinkText1", "Contact", new { requestId = ViewContext.RouteData.Values["requestId"] })
当我在操作参数之前移动requestId参数时,它的工作方式与我预期的一样,但我不想移动它:
routes.MapRoute(
name: "Testroute",
url: "home/{requestId}/{action}",
defaults: new { controller = "Home", action = "Index" }
);
有人能给我解释一下这种行为吗?如何在不明确指定参数的情况下使其工作?InControl智能驭享:
将int替换为可为null的int
对于路由:
在路由中将requestId设置为可选
routes.MapRoute(
name: "Testroute",
url: "home/{action}/{requestId}",
defaults: new { controller = "Home", action = "Index" ,requestId=RouteParameter.Optional }
);
我有同样的问题\不幸的是,我打电话时的行为还是一样的。我希望在所有链接中都包含请求参数“8”。
routes.MapRoute(
name: "Testroute",
url: "home/{requestId}/{action}",
defaults: new { controller = "Home", action = "Index" }
);
routes.MapRoute(
name: "Testroute",
url: "home/{action}/{requestId}",
defaults: new { controller = "Home", action = "Index" ,requestId=RouteParameter.Optional }
);