Tuesday 28 November 2017

Overload MVC Action methods

Can we overload MVC Action methods ?

Step 1 : Create on MVC application with controller Customer then write the below code.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace ThreadStarvation.Controllers
{
public class CustomerController : Controller
{
//GET: Customer
public ActionResult Index()
{
return View();
}
public ActionResult GetCustomer()
{
return Content("This is simple");
}
public ActionResult GetCustomer(string CustomerCode)
{
return Content("this is Overloaded");
}
}
}

above code 2 methods with the same name and different parameters it is an function overloading if you build the application then it is build successfully hence function overloading is possible in MVC is show below screen.
















But if you run the application then we got the below error.


















Step 2 : so function overloading in mvc is an yse and no both so how two handle this using the "ActionName" attribute so the ActionName it is an mapper between the HTTP URL and C# code
HTTP URL<---->ActionName <--->c#
Code changes write in below.



using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace ThreadStarvation.Controllers
{
public class CustomerController : Controller
{
//GET: Customer
public ActionResult Index()
{
return View();
}
public ActionResult GetCustomer()
{
return Content("This is simple");
}
[ActionName ("GetCustomerOverload")]
public ActionResult GetCustomer(string CustomerCode)
{
return Content("this is Overloaded");
}
}
}

After run the application then display the out put of function overloading. 
























Second overload method call then display output below.


No comments:

Post a Comment