避免在mvc3中使用带字符串参数的索引表单Url

本文关键字:参数 字符串 索引 Url 表单 mvc3 | 更新日期: 2023-09-27 18:29:42

我有一个类似的控制器操作

    [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 中不提及索引的情况下,调用报表控制器的正确方法是什么?

避免在mvc3中使用带字符串参数的索引表单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时,我正在点击报表控制器索引操作。当我使用/Home/About时,我正要转到关于家庭控制器的操作。所有其他默认路由都按预期运行。