Can you overload controller methods in ASP.NET MVC?

前端 未结 17 1902
无人共我
无人共我 2020-11-22 08:10

I\'m curious to see if you can overload controller methods in ASP.NET MVC. Whenever I try, I get the error below. The two methods accept different arguments. Is this some

17条回答
  •  天涯浪人
    2020-11-22 08:37

    I have achieved this with the help of Attribute Routing in MVC5. Admittedly I am new to MVC coming from a decade of web development using WebForms, but the following has worked for me. Unlike the accepted answer this allows all the overloaded actions to be rendered by the same view file.

    First enable Attribute Routing in App_Start/RouteConfig.cs.

    public class RouteConfig
    {
        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
    
            routes.MapMvcAttributeRoutes();
    
            routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
            );            
        }
    }
    

    Optionally decorate your controller class with a default route prefix.

    [RoutePrefix("Returns")]
    public class ReturnsController : BaseController
    {
        //.......
    

    Then decorate your controller actions that overload each other with a common route and parameters to suit. Using type constrained parameters you can use the same URI format with IDs of different types.

    [HttpGet]
    // Returns
    public ActionResult Index()
    {
        //.....
    }
    
    [HttpGet]
    [Route("View")]
    // Returns/View
    public ActionResult View()
    {
        // I wouldn't really do this but it proves the concept.
        int id = 7026;
        return View(id);
    }
    
    [HttpGet]
    [Route("View/{id:int}")]
    // Returns/View/7003
    public ActionResult View(int id)
    {
        //.....
    }
    
    [HttpGet]
    [Route("View/{id:Guid}")]
    // Returns/View/99300046-0ba4-47db-81bf-ba6e3ac3cf01
    public ActionResult View(Guid id)
    {
        //.....
    }
    

    Hope this helps and is not leading somebody down the wrong path. :-)

提交回复
热议问题