避免在 mvc3 中使用带字符串参数的索引形式 Url
Avoid Index form Url with string parameter in mvc3
我有一个这样的控制器动作
[HttpGet]
public ActionResult Index(string Id)
{
}
所以实际调用就像 Report/Index/{string_param_value}
我想避免像 Report/{string_param_value} 这样的索引,为此
我在 Global.asax.cs
中做了以下更改
routes.MapRoute(
"Report_WithoutIndex",
"Report/{Id}",
new { controller = "Report", action = "Index" }
);
但是这个没有调用索引操作
我试过这个
routes.MapRoute(
name: "Index",
url: "{controller}/{id}",
defaults: new { action = "Index" },
constraints: new { action = "Index" }
);
这个对我有用但是在这之后所有其他的动作都坏了
那么在 url
中调用报告控制器而不提及索引的正确解决方法是什么
关注 RounteConfig.cs
,对我有用 -
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Report_WithoutIndex",
"Report/{Id}",
new { controller = "Report", action = "Index" }
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
我的控制器是 -
public class HomeController : Controller
{
public ActionResult Index()
{
ViewBag.Message = "Modify this template to jump-start your ASP.NET MVC application.";
return View();
}
public ActionResult About()
{
ViewBag.Message = "Your app description page.";
return View();
}
}
public class ReportController : Controller
{
public ActionResult Index(string Id)
{
return null;
}
}
当我使用 /Report/2
时,我正在点击 Report controller Index Action。当我使用 /Home/About
时,我要转到关于家庭控制器的操作。所有其他默认路由都按预期工作。
我有一个这样的控制器动作
[HttpGet]
public ActionResult Index(string Id)
{
}
所以实际调用就像 Report/Index/{string_param_value}
我想避免像 Report/{string_param_value} 这样的索引,为此 我在 Global.asax.cs
中做了以下更改 routes.MapRoute(
"Report_WithoutIndex",
"Report/{Id}",
new { controller = "Report", action = "Index" }
);
但是这个没有调用索引操作 我试过这个
routes.MapRoute(
name: "Index",
url: "{controller}/{id}",
defaults: new { action = "Index" },
constraints: new { action = "Index" }
);
这个对我有用但是在这之后所有其他的动作都坏了
那么在 url
中调用报告控制器而不提及索引的正确解决方法是什么关注 RounteConfig.cs
,对我有用 -
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Report_WithoutIndex",
"Report/{Id}",
new { controller = "Report", action = "Index" }
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
我的控制器是 -
public class HomeController : Controller
{
public ActionResult Index()
{
ViewBag.Message = "Modify this template to jump-start your ASP.NET MVC application.";
return View();
}
public ActionResult About()
{
ViewBag.Message = "Your app description page.";
return View();
}
}
public class ReportController : Controller
{
public ActionResult Index(string Id)
{
return null;
}
}
当我使用 /Report/2
时,我正在点击 Report controller Index Action。当我使用 /Home/About
时,我要转到关于家庭控制器的操作。所有其他默认路由都按预期工作。