Bind Single View With Multiple ActionMethod

Introduction

This article provides an example of attaching a single view with multiple actions. We create two actions in a single controller and both are called by the single view.

Let's see an example of attaching a single view with multiple actions.

Step 1

Create an application as in the following:

  • Start Visual Studio 2012.
  • From the start window select "Installed" -> "Visual C#" -> "Web".
  • Select "ASP.NET MVC4 Web Application" and click on the "OK" button.

    Select MVC4 Web Application

  • From the "MVC4 Project" window select "Web API".

    Select WebAPI

  • Click on the "OK" button.

Step 2

Add two action methods in the HomeController.

  • In the "Solution Explorer".
  • Select "Controller" -> "HomeController".

    Select HomeController
Add the following Code:
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.Mvc;  
  6. using MvcApplication11.Models;  
  7. namespace MvcApplication11.Controllers  
  8. {  
  9.     public class HomeController : Controller  
  10.     {  
  11.         public ActionResult Show()  
  12.         {  
  13.             ViewBag.ActionName = "Show";  
  14.             return View("Display");  
  15.         }  
  16.         public ActionResult Show2()  
  17.         {  
  18.             ViewBag.ActionName = "Show2";  
  19.             return View("Display");  
  20.         }  
  21.     }  
  22. }   

Step 3

Now add a MVC4 View Page (aspx) in the Shared folder:

  • In the "Solution Explorer".

  • Right-click on the "Shared" folder and select "Add" -> "New Item".

  • Select "Installed" -> "Visual C#" -> "Web" and select  MVC4 View Page (aspx).

    Create ViewPage(aspx)

  • Click on the "Add" button.

Add the following code:

  1. <%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<MvcApplication11.Models.Customer>" %>  
  2. <!DOCTYPE html>  
  3. <html>  
  4. <head runat="server">  
  5.     <meta name="viewport" content="width=device-width" />  
  6.     <title></title>  
  7. </head>  
  8. <body>  
  9.     <div>  
  10.      <% var ActionName = ViewBag.Controller; %>  
  11.         <% if (ActionName == "Home")  
  12.            {%>  
  13.            This is the first Action method  
  14.            <%}  
  15.            else  
  16.            {%>  
  17.               This is the Second Action method  
  18.            <%} %>  
  19.     </div>  
  20. </body>  
  21. </html>   

Step 4

Execute the application  and change the URL to http://localhost:55615/Home/Show.

Calling ActionMethod1

Now change the URL to http://localhost:55615/Home/Show2

Calling ActionMethod2


Similar Articles