Can you overload controller methods in ASP.NET MVC?

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

    No,No and No. Go and try the controller code below where we have the "LoadCustomer" overloaded.

    public class CustomerController : Controller
        {
            //
            // GET: /Customer/
    
            public ActionResult LoadCustomer()
            {
                return Content("LoadCustomer");
            }
            public ActionResult LoadCustomer(string str)
            {
                return Content("LoadCustomer with a string");
            }
        }
    

    If you try to invoke the "LoadCustomer" action you will get error as shown in the below figure.

    enter image description here

    Polymorphism is a part of C# programming while HTTP is a protocol. HTTP does not understand polymorphism. HTTP works on the concept's or URL and URL can only have unique name's. So HTTP does not implement polymorphism.

    In order to fix the same we need to use "ActionName" attribute.

    public class CustomerController : Controller
        {
            //
            // GET: /Customer/
    
            public ActionResult LoadCustomer()
            {
                return Content("LoadCustomer");
            }
    
            [ActionName("LoadCustomerbyName")]
            public ActionResult LoadCustomer(string str)
            {
                return Content("LoadCustomer with a string");
            }
        }
    

    So now if you make a call to URL "Customer/LoadCustomer" the "LoadCustomer" action will be invoked and with URL structure "Customer/LoadCustomerByName" the "LoadCustomer(string str)" will be invoked.

    enter image description here

    enter image description here

    The above answer i have taken from this codeproject article --> MVC Action overloading

提交回复
热议问题