我有一个带有两个参数的动作,但是当调用动作时,参数在URL中显示为查询字符串,如下所示:
localhost:34795/Verification?DepartmentID=3&SubDepartmentID=2
我知道使用自定义网址路由我可以将其更改为:
本地主机:34795 /验证/ 3/2
但我无法做到这一点我将此代码添加到Globas.asax但直到"
没有结果public class MvcApplication : System.Web.HttpApplication
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute( "Blog", // Route name
"Verification/{DepartmentID}/{SubDepartmentID}", // URL with parameters
new { controller = "Verification", action = "Index" } // Parameter defaults
);
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
//routes.MapRoute(
// "Default", // Route name
// "{controller}/{action}/{id}", // URL with parameters
// new { controller = "TestDetails", action = "GetSubDepartmentID", id = "" } // Parameter defaults
//);
}
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
WebApiConfig.Register(GlobalConfiguration.Configuration);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
AuthConfig.RegisterAuth();
}
}
我这样做但没有发生什么,我做错了什么?
答案 0 :(得分:2)
这应该可以解决问题:
routes.MapRoute("Blog",
"Verification/{DepartmentID}/{SubDepartmentID}",
new {
controller = "Verification",
action = "Index",
DepartmentID = UrlParameter.Optional,
SubDepartmentID = UrlParameter.Optional
}
);
然后在VerificationController的Index
函数中:
public ActionResult Index(int DepartmentID, int SubDepartmentID)
答案 1 :(得分:1)
我已经得到了解决方案,经过彻底调试后我意识到在asp.net mvc 4中它默认在应用程序共享目录中创建了一些类,并且注册路由应用程序正在调用此方法:
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
WebApiConfig.Register(GlobalConfiguration.Configuration);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
AuthConfig.RegisterAuth();
}
你在这里看到它调用RegisterRoutes方法,该方法在RouteConfig.cs文件中,这意味着在RouteConfig类中它没有调用Global.asax的方法,这是问题,我疯了解决它,最后这个结果我得到了得到了工作。
这是我的RouteConfig.cs代码,它解决了问题并使事情有效:
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute("home", "", new { controller = "Home", action = "Index" });
routes.MapRoute(
"Verification", // Route name
"Verification/{DepartmentID}/{SubDepartmentID}", // URL with parameters
new
{
controller = "Verification",
action = "Index",
DepartmentID = UrlParameter.Optional,
SubDepartmentID = UrlParameter.Optional
} // Parameter defaults
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
}