Introduction
In previous articles we have seen about what is Model-View-Controller, how to install MVC 3, what is Razor view engine and its syntax. Now this article explains how to create an application with MVC 3 razor.
First MVC 3 Razor Application
The best way to learn MVC 3 is to work on it with the examples. So we start our first application with an example. To create a new mvc project; open vs2010, click on menu New -> New Project.

From the above screen choose ASP.NET MVC 3 Web Application and name it as 'FirstMVC3Application'. And click on 'OK', which opens the following screen.

From the above select 'Empty' application in Project Templates section and choose viewengine as 'Razor'. Don't check on 'Use HTML5 sementic markup'.
The 'Empty' application creates project with only the minimum files and folders. The 'Internet Application' creates project with an example which include user registration and authentication, navigation, and a consistent layout. The 'Intranet Application' option is similar to Internet Application, but is designed for use in environments that authenticate users through a domain/Active Directory infrastructure.
After you click on 'OK' button, visual studio creates the project with some files and folders as shown below.

Adding First Controller
Why we first add a controller? The answer is in MVC all incoming requests are handled by 'Controllers'. Controllers are nothing but C# classes which are derived from System.Web.Mvc.Controller class. Each public method in a controller is called as an 'Action'. This method/action can be invoked from web via a URL to complete this action. In coming articles we'll see how these actions are invoked in different ways depending on the requirement.
To create a new controller open solution explorer, right click on Controllers folder and choose Add -> Controller as shown in below figure.

By clicking on Add -> Controller, the Add Controller dialog box appears as shown below. Give a name to your controller, but the name should end with 'Controller'. Here type controller name as 'HomeController'. In scaffolding options section choose 'Empty'. It allows to create a controller with a template which has common functions.

Note: The MVC convention is to put all controllers in 'Controllers' folder which created by Visual Studio at the time of project creation. But this is not mandatory.
Click the 'Add' button, now the controller with name 'HomeController' is created in the controllers folder.You can observe that the class 'HomeController' is derived from System.Web.Mvc.Controller. An action 'Index' is added by default and its return type is 'ActionResult' which returns a View.

ActionResult: An action result represents a command that the framework will perform on behalf of the action method. The ActionResult class is the base class for action results. The types that derived from ActionResult are as follows:
- ContentResult
- EmptyResult
- FileResult
- HttpUnauthorizedResult
- JavaScriptResult
- JsonResult
- RedirectResult
- RedirectToRouteResult
- ViewResultBase
The ViewResultBase class is the abstract base class for both the ViewResult and PartialViewResult classes. If you want an action method to result in a rendered view, the action method should return a call to the controller's 'View' helper method. The View helper method passes a ViewResult object to the ASP.NET MVC framework, which calls the object's ExecuteResult method. The other actionresults are explained in some other article with examples.
Adding a View to Controller: Adding a view to controller is simple. In the HomeController right click on Index() then a popup will be shown.

From that popup click on 'Add View'. Now the screen will be as shown below.

Keep the view name as it is. Select View engine as 'Razor(cshtml)' because we want to work with razor. You can uncheck 'Use a layout or master page', if you don't want to use any layout or master pages. Here it is kept checked. Click on 'Add' button, Visual Studio will create a new view file called 'Index.cshtml', in the Views/Home folder.
Now go to Views - >Home and open Index.cshtml file. The file will be as shon below.
@{ ViewBag.Title = "Index"; } <h2>Index</h2>
In this page we have one new thing 'ViewBag.Title'. ViewBag is used to pass dynamic data from controller to view or ViewBag is a dynamic object to which you can assign arbitrary properties, making those values available in whatever view is subsequently rendered.
In the Index.cshtml page we are assigning value "Index" to ViewBag.Title. And this value is accessing in the _Layout.cshtml page. You can find _Layout.cshtml at Views/Shared loaction and open it.

In _Layout.cshtml page can find '@RenderBody()' in the body section. As said earlier _Layout.cshtml is like masterpage in Asp.Net web forms and '@RenderBody()' is like the ContentPlaceHolder server control in Asp.Net webforms. But here only one RenderBody method per Layout page is allowed. About layouts are explained in other article in detail.
Select Start Debugging from the Debug menu to run the application and test view. You can see the following output.

Now the question is how this view is rendered into the browser. You can say that this view is returned by the action Index in the HomeController class. But who called this Index action and how does MVC know to call this method initially(at the time of application loading)?
The answer is Asp.Net 'routing system'. which decides how URLs map to particular controllers and actions. ASP.NET Mvc has powerful routing engine which allows mapping between url routes and controller action. In the Global.asax file these routes are applied in the RegisterRoutes() method as shown below.
public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.MapRoute( "Default", // Route name "{controller}/{action}/{id}", // URL with parameters new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults ); }
The route with the pattern {resource}.axd/{*pathInfo} is included to prevent requests for the Web resource files such as WebResource.axd or ScriptResource.axd from being passed to a controller.
In the above MapRoute method it has 3 parameters. The first parameter is the name of the route, and it is important for debugging – in order to know which route matches an input url. The second is the route URL with parameters, and the third parameter is default values for the above parameters. In the above MpRoute method 'Default' is the route name, which maps to an action 'Index' in the controller 'Home'. That is the reason why we have taken our first controller name as 'HomeController'. In some other artcile, detailed MVC Routing will be explained.
This is how to create your first MVC3 application in VS 2010. And in next article we cover about Layout, ResnderSection and RenderBody in _Layout.cshtml page.
Comments/Suggestions are invited. Happy coding......!
Comments Post a Comment