Can you overload controller methods in ASP.NET MVC?

前端 未结 17 1662
无人共我
无人共我 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:32

    You could use a single ActionResult to deal with both Post and Get:

    public ActionResult Example() {
       if (Request.HttpMethod.ToUpperInvariant() == "GET") {
        // GET
       }
       else if (Request.HttpMethod.ToUpperInvariant() == "POST") {
         // Post  
       }
    }
    

    Useful if your Get and Post methods have matching signatures.

    0 讨论(0)
  • 2020-11-22 08:33

    You can use the attribute if you want your code to do overloading.

    [ActionName("MyOverloadedName")]
    

    But, you'll have to use a different action name for the same http method (as others have said). So it's just semantics at that point. Would you rather have the name in your code or your attribute?

    Phil has an article related to this: http://haacked.com/archive/2008/08/29/how-a-method-becomes-an-action.aspx

    0 讨论(0)
  • 2020-11-22 08:33

    Sorry for the delay. I was with the same problem and I found a link with good answers, could that will help new guys

    All credits for BinaryIntellect web site and the authors

    Basically, there are four situations: using differents verbs, using routing, overload marking with [NoAction] attribute and change the action attribute name with [ActionName]

    So, depends that's your requiriments and your situation.

    Howsoever, follow the link:

    Link: http://www.binaryintellect.net/articles/8f9d9a8f-7abf-4df6-be8a-9895882ab562.aspx

    0 讨论(0)
  • 2020-11-22 08:34

    If this is an attempt to use one GET action for several views that POST to several actions with different models, then try add a GET action for each POST action that redirects to the first GET to prevent 404 on refresh.

    Long shot but common scenario.

    0 讨论(0)
  • 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. :-)

    0 讨论(0)
  • 2020-11-22 08:39

    I like this answer posted in another thread

    This is mainly used if you inherit from another controller and want to override an acction from the base controller

    ASP.NET MVC - Overriding an action with differing parameters

    0 讨论(0)
提交回复
热议问题