Can we make an overloaded controller method in ASP.NET MVC

I am developing an ASP.Net MVC project, but I cannot overload Index () even when I defined a different method with a different no. parameters and gave the correct routing for it. But that does not work. So I just want to ask if we can overload methods in the controller or not?

+3
source share
2 answers

Actions of the controller with the same name are possible on one controller if they are called with different HTTP verbs. Example:

public ActionResult Index() 
{
    return View();
}

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(SomeModel model) 
{
   return View();
}

When you call GET /Controller/Index, the first action is called, and when you call POST /Controller/Index, the second action is called.

+6
source

, ( , , , NonAction ActionName). ActionNameSelectorAttribute , , .

: .

ActionMethodSelectorAttribute, b/c. , ActionNameAttribute. , .

public class AllParamsRequiredAttribute : ActionMethodSelectorAttribute
{
    public override bool IsValidForRequest(ControllerContext controllerContext, System.Reflection.MethodInfo methodInfo)
    {
        var paramList = methodInfo.GetParameters().Select(p => p.Name);
        foreach (var p in paramList)
            if (controllerContext.Controller.ValueProvider.GetValue(controllerContext, p) == null) return false;
        return true;
    }
}

, , , , ValueProvider , . , , , , , ; . , , bool . .

, :

[AllParamsRequired]
public ViewResult Index(int count){/*... your logic ... */}
public ViewResult Index() {/*... more of your logic ... */}

URL- mydomain.com/?count=5 , URL- mydomain.com/ .

0

Source: https://habr.com/ru/post/1734238/


All Articles