Custom Actions in side MVC 3 Controllers
Before reading this blog, make sure that you covered http://www.c-sharpcorner.com/UploadFile/jaishmathews/8821/ which is talking about basic controller functionality in side MVC 3. Usually all Actions in side Views are attached to its controller by specific methods inside the controller file. You just assume actions as files in side Views. Create a new MVC 3 project in VS 2010 and open “MvcApplication1\Controllers\HomeController.cs”. This is the controller for View named Home and you can see 2 files in side this View as like below.
Here is how controller initiating different actions under same View. Open “MvcApplication1\Controllers\HomeController.cs” and locate below lines. As those names reveals each of these methods handling Index & About actions respectively.
public ActionResult Index()
{
ViewBag.Message = "Welcome to ASP.NET MVC!";
return View();
}
public ActionResult About()
{
return View();
}
But matter is that in a scenario like we need to use “EmailApplicationIndex” or “DataExortIndex” like that. Please rename the Index Action method like below and run the application and enjoy the error getting. Please see the screen shot.
public ActionResult EmailApplicationIndex()
{
ViewBag.Message = "Welcome to ASP.NET MVC!";
return View();
}
Application has Index.cshtml and it could not find it's action method in side controller file. Below is the proof, if you are more enthusiasts. It has been highlighted the line in side global.asax where it defined default route for the application.
So how we can make both, i.e. you need to use custom action method name and action should work on this. Here need to use ActionName attribute as below. This will re assign the Index action with corresponding Controller/ActionMethod
[ActionName("Index")]
public ActionResult EmailApplicationIndex()
{
ViewBag.Message = "Welcome to ASP.NET MVC!";
return View();
}
Practical usage of ActionName is along with HttpGet & HttPost attributes. These attributes are using to handle Get action during data edit and also Post action during submission. I will get back with an article on this too. Thanks for reading this.