₹2,000.00 ₹300.00
  • 11 students
  • 6 lessons
  • 0 quizzes
  • 10 week duration


Starting MVC — Chapter 1. Controllers and Views Basic

The Controller.


Understand Controller in ASP.NET MVC?

In order to understand Controller first we need to understand the term

User interaction logic. What is User Interaction logic??

Scenario 1

Did you ever give a thought what happens, when an end user hits a URL (Uniform Resource Locator) on a browser. In the beginning, browser sends a request to server and server sends a response.



Understand Controller in ASP.NET MVC? In order to understand Controller first we need to understand the term User interaction logic.

What is User Interaction logic?? Scenario 1 Did you ever give a thought what happens, when an end user hits a URL (Uniform Resource Locator) on a browser. In the beginning, browser sends a request to server and server sends a response.




By sending such request, client is trying to interact with server. Server is able to respond back because some logic is written at the server end to fulfil this request. Some logic??, so what exactly can be this logic? Logic will handle the user requests and user’s interaction with server. In short User Interaction Logic.

Scenario 2

It is also possible that response sent by Server is an HTML response, which may consist of couple of input controls and a submit button. What will happen when “Save Customer” button is clicked? If your answer is “Some event handler will handle the button click”, then sorry L. “Like all other Web programming technologies ASP.NET won’t really a concept of events. In case of ASP.NET Web Forms Microsoft wrote some code on behalf of us and brought us the feeling of event driven programming. It’s just an abstraction or the right word would be illusion.” In reality when button is clicked a simple HTTP (HyperText Transfer Protocol) request is sent to the server. This time the difference is, values in the “Customer Name”, “Address” and “Age” textboxes will be sent along with request. (In technical terms “values are posted to the server”). Now if it’s a request then there must be a logic written in the server so that server can send back the response. In short there must be some user interaction logic written on the server. In ASP.NET MVC, the last letter C indicates Controller and it is the one who will handle the user


Understand Views in ASP.NET MVC As we discussed earlier Controller will handle the user’s requests and send the response. Most common the response is HTML response. HTML response may contain some images, texts, Input controls, etc. It will represent an UI. Normally in technical world layer defining the user interface design is termed as UI layer and in MVC it is termed as View. Lab 1 – Demonstrating Controller Step 1 – Create MVC 5 Project Step 1.1: Open Visual Studio 2013(or higher). Click on File>>New>>Project. A New Project dialog box appears. Step 1.2: Select Web Application. Enter name in Name bar and location in Location bar, and press OK



Step 1.3: Select MVC template.

Step 1.4: Click Change Authentication button and then select “No Authentication” radio button from “Change Authentication” dialog box and click “OK”.


Step 2 – Create Controller Step 2.1: In the Solution Explorer, right click the Controllers folder and select Add>>Controller….


Step 2.2: Select “MVC 5 Controller – Empty” and click “Add”.


Step 2.3: Put Controller name as “TestController” and click “Add”. Make sure not to delete the word Controller. Controller name must be suffixed with “Controller”.


It will create a new class called TestController. Keep one thing in mind that class name is TestController but Controller name is “Test”. We will talk about it in detail soon. Step 3 – Create Action Method Open newly created TestController class. You will find a method inside it called “Index”. Remove that method and add a new public method called “GetString” as follows: public class TestController: Controller { public string GetString() { return “Hello World is old now. It’s time for wassup bro ;)”; } }

Step 4 – Execute and Test Press F5. In the address bar put “ControllerName/ActionName” as follows: (Controller name is Test).



Talk on Lab 1

What is the relationship between TestController and Test? TestController is the class name whereas Test is the Controller name. When you type Controller name in the URL it should be without the word Controller. Every public class which inherits from “Controller” base class and contains suffix Controller will become Controller in the project. What is Action Method? Action method is simply a public method inside Controller which accepts user’s request and returns some response. In above example, action method “GetString” returns a string response type. Note: In ASP.NET Web Forms default response is always HTML. When we want to return something other than HTML, we create HTTP Handlers, override content type, do Response.End, etc. It’s not an easy task. In ASP.NET MVC it’s very easy. If return type is ‘string’ you can just return string , you do not need to send complete HTML.

What will happen if we try to return an object from an action method? Look at the following code block. namespace WebApplication1.Controllers { public class Customer { public string CustomerName {get; set;} public string Address {get; set;} } public class TestController: Controller { public Customer GetCustomer() { Customer c = new Customer(); c.CustomerName = “Customer 1”; c.Address = “Address1”; return c; } } }



Output of above action method will look as shown below. When return type is object, it will return ‘ToString()’ implementation of that object. By default ‘ToString()’ method returns fully qualified name of the class which is “NameSpace.ClassName”; Can we change the default behavior with object return type? We can achieve it by overriding “ToString” method in Customer class as follows: public override string ToString() { return this.CustomerName+”|”+this.Address; } Press F5. Output will be as follows: Is it must to define action methods with public access modifier? Yes, every public method will become action methods automatically.



Is it must to define action methods with public access modifier? Yes, every public method will become action methods automatically. What about non-public methods? They are simply methods of a class and not avaiLable publicly. In simple words these methods cannot be invoked from the Web. What if we want a method to be public but not action method? Simply decorate it with NonAction attribute as follows: [NonAction] public string SimpleMethod() { return “Hi, I am not action method”; } When we try to make request to above action method we will get the following response:



Lab 2 – Demonstrating Views In the first Lab we created a simple MVC application with just Controller and a simple string return type. Let us go and add View part to the MVC application. Step 1 – Create new action method Add a new action method inside TestController as follows: public ActionResult GetView() { return View(“MyView”); }

Step 2 – Create View Step 2.1: Right click the above action method and select “Add View”. The Add View dialog box appears.




Step 2.2: In the “Add View” dialog box put View name as “MyView”, uncheck “Use a layout page:” checkbox and click “Add”.



It will create a new View inside “Views/Test” folder. Step 3 – Add contents to View Open MyView.cshtml file and add contents as follows: @{ Layout = null; } <!DOCTYPE html> <html> <head> <meta name=”Viewport” content=”width=device-width” /> <title>MyView</title> </head> <body> <div> Welcome to MVC 5 Step-by-step learning </div> </body> </html>


Step 4 – Test and Execute Press F5 to execute the application.



Talk on Lab 2 Why View is placed inside Test Folder? In ASP.NET MVC, every View will be associated with some Controller and hence all Views related to a particular Controller must be placed inside a special folder. This special folder will be named as”ControllerName” and placed inside Views folder in the root location. For every Controller only those Views will be avaiLable which are located inside its own folder. For example, all the Views related to TestController must be placed inside “~/Views/Test” and TestController can access only those Views which are inside Test folder. Can’t we reuse some of the Views across multiple Controllers? Yes, we can. For that we will keep those Views inside a special folder called “Shared”.


Views located inside this Shared folder will be avaiLable to all the Controllers. Is it possible that one action method is referencing more than one Views? Yes. Look at the following code: public ActionResult GetView() { if(Some_Condition_Is_Matching) { return View(“MyView”); } else { return View(“YourView”); } } Note: In MVC Views and Controllers are not tightly coupled. One action method can refer more than one View and one View can be referred by more than one action method (by keeping them in Shared folder). It provides better reusability. What is ActionResult?

What is ViewResult? ViewResult is a result of View. When response need to be a HTML response we return ViewResult.

View function creates ViewResult object which will render View to the response. Render View means creates pure HTML which browser can understand and display. How does View function creates final HTML? l View function creates ViewResult of a View located in either Controller folder or Shared folder. l ViewResult internally creates the object of ViewPageActivator class. l ViewResult chooses the correct ViewEngine and passes ViewPageActivator object as argument to ViewEngine’s constructor. l ViewEngine create the object of View class. l ViewResult invokes the RenderView method of View. If you have not understood this question completely, don’t worry, by the end of the day 7 you will understand everything. ☺ What is the relation between ActionResult and ViewResult? ActionResult is the abstract class whereas ViewResult is a grand child of ActionResult. Grand child because, ViewResult is the child of ViewResultBase and ViewResultBase is the child of ActionResult. If we want to return ViewResult why ActionResult is set as return type?

To achieve polymorphism (one object behaving as multiple forms) look at the following example: public ActionResult GetView() { if(Some_Condition_Is_Matching) { return View(“MyView”); } else { return Content(“Hi Welcome”); } } In the above example, response is not fixed. It can be a simple content result or may be advanced ViewResult. It completely depends on “if…else” condition. If condition leads to true it will return ViewResult or else it will return Content result. What is ContentResult? Just like ViewResult ContentResult is a child of ActionResult. ViewResult represents a complete HTML response whereas ContentResult represents a scalar text response. What is the difference between returning ContentResult and pure string? ContentResult is the ActionResult wrapper around string result. When we return pure string from action method, it actually considered as ContentResult only. Is it possible to invoke View function without Parameter?

Yes, then it will find the View with name “CurrentActionName”.


Next, passing data from Controller to View


Leave a Reply

Your email address will not be published. Required fields are marked *