How to add a Controller in MVC5

First create new empty mvc project.
ASP.NET MVC5

















In Solution  Explorer, right-click the Controllers folder  and then click Add,  then Controller.

CONTROLLER
















In the Add Scaffold dialog box, click MVC 5  Controller - Empty, and then click Add.CONTROLLER

Name your new controller "HomeController" and click Add.


CONTROLLER

In Solution  Explorer that a new file  has been created named HomeController.cs and a new folderViews\Home. HomeController.cs file is open in the IDE.

Replace the contents of the file with the following code.

CONTROLLER ACTION

The controller methods will return a string of HTML as an example. The controller is named Home and  the first action named Index.  Let’s invoke it from a browser. Run the application (press F5 or Ctrl+F5). In the  browser, append "Home" to the path in the address bar. (For example,  in the illustration below, it's http://localhost:50263/Home.)  The page in the browser will look like the following screenshot. In the action above, the code returned a string directly. You told the system to just return some HTML, and it did! 

MVC APPLICATION
ASP.NET MVC invokes different controller classes (and different action methods within  them) depending on the incoming URL. The default URL routing logic used by ASP.NET  MVC uses a format like this to determine what code to invoke:
/[Controller]/[ActionName]/[Parameters]
You set the format for routing in the App_Start/RouteConfig.cs  file.

route config


When you run the application and don't supply any URL segments, it defaults to  the "Home" controller and the "Index" action method specified in the defaults  section of the code above. 

Now Add Welcome action in HomeController.cs file. Add the following code in your file.

 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:50263/Home/Welcome?name=M9coders&numtimes=9).
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.


mvc




Post a Comment