【问题标题】:Method over loading in homecontroller and routing issue in asp.net mvc家庭控制器中的方法重载和 asp.net mvc 中的路由问题
【发布时间】:2012-08-03 02:35:46
【问题描述】:

我有家庭控制器。我的家庭控制器有两种索引方法,一种无参数,一种有参数。就像

    public ActionResult Index()
    {
        ViewData["Message"] = "Welcome to ASP.NET MVC!";
        return View("index");
    }

    public ActionResult Index(int a)
    {
        ViewData["Message"] = "Welcome to ASP.NET MVC! and Your Age is " + a;
        return View();
    }

我在 global.asax 中只定义了两个路由条目

            routes.MapRoute(
                "Default1", // Route name
                "{Home}/{ID}", // URL with parameters
                new { controller = "Home", action = "Index", id = UrlParameter.Optional }
            );

            routes.MapRoute(
                "Default", // Route name
                "{controller}", // URL with parameters
                new { controller = "Home", action = "Index", id = UrlParameter.Optional }
            );

我希望当我输入像 http://localhost:7221http://localhost:7221/home 这样的 url 然后 index() 方法没有参数的家庭控制器应该触发和

当我键入 http://localhost:7221/home/77 时,带有家庭控制器参数的 index(int a) 方法应该会触发。但我收到错误,为什么我输入了我指定的两种 url。错误信息是 当前对控制器类型“HomeController”的操作“Index”的请求在以下操作方法之间不明确: System.Web.Mvc.ActionResult Index() 在 BeginnerMVC.Controllers.HomeController 类型上 类型 BeginnerMVC.Controllers.HomeController 上的 System.Web.Mvc.ActionResult Index(Int32)

我无法捕捉到错误。我的路由代码有什么问题。请帮忙。谢谢

【问题讨论】:

    标签: asp.net-mvc


    【解决方案1】:

    您不能在 MVC 中将方法重载与操作一起使用。如果您详细说明您要达到的目标,您会得到有关如何做到这一点的建议。

    【讨论】:

    • 请告诉我为什么在 mvc 动作的情况下方法重载是不可能的。
    • @Thomas 简而言之,“这种行为是设计使然”。路由的工作方式和解析动作名称的方式阻止了使用重载,因为根据定义,重载共享相同的名称,并且路由中的动作只是一个名称,因此无法找到正确的方法。跨度>
    猜你喜欢
    • 1970-01-01
    • 2020-02-19
    • 2013-06-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多