Add a Controller in MVC

Let's discuss how to add Controller in an MVC application:


  •  Just go in to solution explorer of your application -> Controller -> Add ->Controller,just like in the billow image:

 


 

  •    A new dialogue box ll open click on add, do like bellow image :


 

 

  •   A new HelloworldController.cs file ll be available in controller folder in solution explorer,just like in below image:

 

  • Replace the default code to :

using System.Web;
using System.Web.Mvc; 
 
namespace MvcMovie.Controllers 
{ 
    
public class HelloWorldController : Controller 
    
{ 
        
// 
        // GET: /HelloWorld/ 
 
        
public string Index() 
        
{ 
            
return "This is my <b>default</b> action..."; 
        
} 
 
        
// 
        // GET: /HelloWorld/Welcome/ 
 
        
public string Welcome() 
        
{ 
            
return "This is the Welcome action method..."; 
        
} 
    
} 
}

        

       

      

   

      

Let's modify the example slightly so that you can pass some parameter information from the URL to the controller (for example, /HelloWorld/Welcome?name=Scott&numtimes=4). Change your Welcome method to include two parameters as shown below. Note that the code uses the C# optional-parameter feature to indicate that thenumTimes parameter should default to 1 if no value is passed for that parameter.

public string Welcome(string name, int numTimes = 1) {
     
return HttpUtility.HtmlEncode("Hello " + name + ", NumTimes is: " + numTimes);
}


Run your application and browse to the example URL (http://localhost:xxxx/HelloWorld/Welcome?name=Scott&numtimes=4). You can try different values for 
name and numtimes in the URL. The ASP.NET MVC model binding system automatically maps the named parameters from the query string in the address bar to parameters in your method.like the bellow image:

 

 

In both these examples the controller has been doing the "VC" portion of MVC — that is, the view and controller work. The controller is returning HTML directly. Ordinarily you don't want controllers returning HTML directly, since that becomes very cumbersome to code. Instead we'll typically use a separate view template file to help generate the HTML response. Let's look next at how we can do this.


Thanks

Neha Sharma

Ebook Download
View all
Learn
View all