Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / web / ASP.NET

Learn MVC (Model view controller) Step by Step in 7days – Day 6

4.93/5 (60 votes)
13 Jan 2015CPOL14 min read 197.4K  
This article is Day 6 of learn MVC step by step in 7 days.

MVC 2 is quiet old and this article was written long years back. We would recommend you to start reading from our fresh Learn MVC 5 step by step series from here: -http://www.codeproject.com/Articles/866143/Learn-MVC-step-by-step-in-days-Day

Content

So, what’s the agenda for MVC day 6?

Day 1:-Controllers, strong typed views and helper classes

Day 2:- Unit test, routing and outbound URLS

Day 3:- Partial views, Data annotations,Razor, Authentication and Authorization

Day 4:- JSON ,Jquery, State management and Asynch controllers

Day 5 :- Bundling, Minification , ViewModel , Exception handling and areas

Lab 22:- Display modes (MVCMobile)

Introduction

Step 1:- Create appropriate pages

Step 2:- That’s it, solet’s test.

Step 3:- More customization and control

Step 4:- Test your mobile customization

Lab 23:- MVC OAuth provider

Step 1: - Register your application and get the ID and Key

Step 2: - Create a MVC site for authenticating with OAuth

Step 3 :Start browsing

Lab 24:- MVC Model Binders

Introduction

Step 1: - Create “EnterCustomer.aspx” and the controller

Step 2: - Create Customer model

Step 3: - Create binder which does mapping.

Step 4: - Attach the mapper with the action

Step 5: - Enjoy your output

Lab 25:- Razor Layout

Introduction

Step 1: - Create Layout page

Step 2: - Create view and apply the layout

Step 3: - Create a controller and see your layout in action

Lab 26 :- Custom Html Helper methods

Introduction

Step 1 :- Create a MVC project with simple class file

Step 2: Mark the class as Static and add methods

Step 3: Use the Helper class.

What is for the Lastday?

Are you completely new to MVC?

Do not miss MVC interview questions with answers

So, what’s the agenda for MVC day 6?

For day 6 we have five great labs: -

  • Mobile support using the “DisplayMode” feature.
  • Integrate your application using Facebook, twitter or any other third party sites by using “OAuth”.
  • Using model binders to bind UI and your model classes if the property names are different.
  • Razor Layout’s.
  • Creating your own Custom view engine.

In case you have missed the previous days of Asp.net MVC tutorials, below are the links with what topics are covered.

Day 1:-Controllers, strong typed views and helper classes

http://www.codeproject.com/Articles/207797/Learn-MVC-Model-view-controller-Step-by-Step-in-7

Day 2:- Unit test, routing and outbound URLS

http://www.codeproject.com/Articles/259560/Learn-MVC-Model-view-controller-Step-by-Step-in-7

Day 3:- Partial views, Data annotations,Razor, Authentication and Authorization

http://www.codeproject.com/Articles/375182/Learn-MVC-Model-View-Controller-Step-by-Step-in-7

Day 4:- JSON ,Jquery, State management and Asynch controllers

http://www.codeproject.com/Articles/375182/Learn-MVC-Model-View-Controller-Step-by-Step-in-7

Day 5 :- Bundling, Minification , ViewModel , Exception handling and areas

http://www.codeproject.com/Articles/724559/Learn-MVC-Model-view-controller-Step-by-Step-in-7

Lab 22:- Display modes (MVCMobile)

Introduction

It’s a world of small devices i.e. mobile. As a MVC developerand we expect a lot of support from

Microsoft MVC template for the same. Now desktop screen’s and mobile screens have a huge variation in size.

Image 1

So we would like to create different screens for desktop and different screens for mobile. For example we would create “Home.aspx” for normal desktop and “Home.mobile.aspx” for mobile. If MVC can automatically detect the device type and render the appropriate page that would save lot of work. This is automated by using “MVC Display Mode”.

When any HTTP request comes to a web application this HTTP request has a value called as “User Agent”. This “User Agent” value is used by MVC display mode and appropriate view is picked and rendered as per device. So let’s do a demo and see it live in blood and flesh.

Step 1:- Create appropriate pages

So let’s a create a sample MVC project which has two views “Index.aspx” for desktop and “Index.Mobile.aspx” for mobile as shown in the below figure.

Image 2

Also let’s add a controller called as “Home” controller which will invoke the “Index” view.

Note :-You can see in the below code snippet we have created an action result as index. Because our view name and action name are same, we do not need to pass the view name in the “return View();”.

HTML
publicclassHomeController : Controller
{
publicActionResult Index()
        {
return View();
        }
}

Step 2:- That’s it, solet’s test.

And that’s all we need to do. Now let’s go and test if MVC display mode lives up to its promise.

So now if you go and hit the controller and action from the browser you will see the below left hand side output. If you hit the same controller and action using the android mobile emulator you will see the right part of the screen.

Image 3

For simulating mobile testing in this lab we have used “Opera mobile” simulator. You can download the emulator from http://dev.opera.com/articles/opera-mobile-emulator/

Step 3:- More customization and control

But what if we want more customization and control:-

  • If Desktop show “Index.aspx”.
  • If mobile show “Index.mobile.aspx”.
  • If Android mobile show “Index.Andriod.aspx”.

We have already implemented the first two conditions. Now for the third condition we need to perform some more extra steps. Relax they are absolutely small and baby steps but with great end results.

First step is to add one more page “Index.android.aspx” especially for android in your views folder as shown in the below figure.

The next step is to make some changes in your “Global.asax.cs” file. The first step is to add “Webpages” namespace as shown in the below figure.

Image 4

The next step is to make some changes in your “Global.asax.cs” file. The first step is to add “Webpages” namespace as shown in the below figure.

HTML
using System.Web.WebPages;

Second step is to use the “DisplayModeProvider” class and add an “Android” entry in to the “Modes” collection as shown in the below code snippet. The below code searches for the string “Android” and if found it tries to render the “Index.Android.aspx” page.

HTML
protectedvoid Application_Start()
{
DisplayModeProvider.Instance.Modes.
                Insert(0, newDefaultDisplayMode("Android")
            {
                ContextCondition = (context => context.
                    GetOverriddenUserAgent().IndexOf("Android", 
StringComparison.OrdinalIgnoreCase) >= 0)
            });
}

Step 4:- Test your mobile customization

Now if you run the opera mobile simulator with Android as the user agent as shown in the below figure ,you will see android page ( Index.android.aspx ) getting rendered.

Image 5

Lab 23:- MVC OAuth provider

One of the most boring processes for an end user is registering on a site. Sometimes those long forms and email validation just puts off the user. So how about making things easy by validating the users using their existing facebook / twitter / linkedin / etc accounts. So the user uses something which he already has while the site is assured that this user is a proper user.

This is achieved by using MVC OAuth (Open standard for authorization).

Image 6

To implement OAuth is a three step process , see the above figure :-

  • Register your App and get ID and Key.
  • Do authentication with the third party site.
  • Once authentication done browse your site.

Step 1 :- Register your application and get the ID and Key

So the first step is to register your APP with the third party site. For this Lab we will use facebook for open authentication. Please note steps will vary for twitter , linked in and other sites. Go to developers.facebook.com and click on “Create new App” menu as shown in the below figure.

Image 7

Give “app name”, ”category” and hit the “create App” button as shown in the below figure.

Image 8

Once the app is registered you need to get “App ID” and “App Secret key” by hitting the show button as shown in the below figure.

Image 9

Step 2 : Create a MVC site for authenticating with OAuth

Now that we have the ID and the key let’s go ahead and create a MVC Internet application. We are creating an internet application so that we get some readymade or you can say template code for “OAuth”.

Image 10

Once the project is created open the “AuthoConfig.cs” from the “App_start” folder.

Image 11

In this config file you will find “RegisterAuth” method and you will see lot of method calls for third party site. Uncomment “RegisterFacebookClient” method and put the ID and the Key as shown in the below code.

HTML
publicstaticclassAuthConfig
{
publicstaticvoidRegisterAuth()
        {
// To let users of this site log in using their accounts from other sites such as Microsoft, Facebook, and Twitter,
// you must update this site. For more information visit http://go.microsoft.com/fwlink/?LinkID=252166

//OAuthWebSecurity.RegisterMicrosoftClient(
//    clientId: "",
//    clientSecret: "");

//OAuthWebSecurity.RegisterTwitterClient(
//    consumerKey: "",
//    consumerSecret: "");

OAuthWebSecurity.RegisterFacebookClient(
                appId: "753839804675146",
                appSecret: "fl776854469e7af9a959359a894a7f1");

//OAuthWebSecurity.RegisterGoogleClient();
        }
}

Run your application and copy the localhost URL name with the port number.

Image 12

Go back to your Developer FB portal , open the App you have just created , click on settings and click “Add platform” as shown in the below figure.

Image 13

It open’s one more dialog box , choose website and click Add.

Image 14

In the URL give your local host URL with the port number as shown in the below figure.

Image 15

Step 3 :Start browsing

That’s it you are all set , now the run the application and click log in.

Image 16

The screen open’s up to two options one at the left hand side is your local login using “Forms” authentication and the right hand side is your third party provided. Click on the facebookbutton , put your credential’s and enjoy the output.

Image 17

Lab 24:- MVC Model Binders

Introduction

In Learn MVC Day 1 lab 5 we had used HTML helper classes to map the HTML UI with the MVC model objects. So below is a simple HTML form which makes a post to “SubmitCustomer” action.

HTML
<formid="frm1" method=post action="/Customer/SubmitCustomer">
            Customer code :- <inputname="CustomerCode"type="text"/>
            Customer name :- <inputname="CustomerName"type="text"/>
    <input type=submit/>
</form>

The “SubmitCustomer” action takes in a customer object. This “Customer” object is produced automatically with the data what is filled in those textboxes without any binding’s and mappings.

HTML
publicclassCustomerController : Controller
{
publicActionResult SubmitCustomer(Customer obj)
{return View("DisplayCustomer");}
}

Do you know why the customer object fills automatically?. It’s because the name of the textboxes and the property names of the customer class is same.

HTML
publicclassCustomer
{
publicstring CustomerCode { get; set; }
publicstring CustomerName { get; set; }
}

But what if the textbox names are not same as the “Customer” class property names.

In other words the HTML text box name is “txtCustomerCode” and the class property name is “CustomerCode”. This is where model binders come in to picture.

Image 18

Model binder maps HTML form elements to the model. It acts like a bridge between HTML UI and MVC model. So let’s do some hand’s on exercise for “ModelBinder”.

Step 1 :- Create “EnterCustomer.aspx” and the controller

The first step is to create “EnterCustomer.aspx” view which will take “Customer” data.

HTML
<formid="frm1" method=post action="/Customer/SubmitCustomer">
            Customer code :- <inputname="TxtCode"type="text"/>
            Customer name :- <input name="TxtName"type="text"/>
    <input type=submit/>
</form>

To invoke this form we need an action in the “Customer” controller because you cannot invoke a view directly in MVC you need to go via the controller.

HTML
publicclassCustomerController : Controller
{
publicActionResult EnterCustomer()
        {
return View();
        }
}

Step 2 :- Create Customer model

The next step is to create a “Customer” model. Please note the property name of the “Customer” class and the HTML UI element textbox names are different.

HTML
publicclassCustomer
{
publicstring CustomerCode { get; set; }
publicstring CustomerName { get; set; }
}

Step 3 :- Create binder which does mapping.

Now because the UI element name and the “Customer” class have different name’s we need to create the “Model” binder. To create the model binder class we need to implement “IModelBinder” interface. In the below code you can see how we have written the mapping code in “BindModel” method.

HTML
publicclassCustomerBinder : IModelBinder
{
publicobject BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
HttpRequestBase request = controllerContext.HttpContext.Request;

string strCustomerCode = request.Form["TxtCode"];
string strCustomerName = request.Form["TxtName"];

returnnewCustomer
            {
                CustomerCode = strCustomerCode,
                CustomerName = strCustomerName
            };
        }
    }

Step 4: - Attach the mapper with the action

So now we have the binder , we have the HTML UI it’s time to connect them. Look at the “SubmitCustomer” action code below. “ModelBinder” attribute binds the binder and the “Customer” object.

HTML
publicclassCustomerController : Controller
{
publicActionResult SubmitCustomer([ModelBinder(typeof(CustomerBinder))]Customer obj) 
{

return View("DisplayCustomer");
}
}

Step 5: - Enjoy your output

So now hit the action (“EnterCustomer”) which invokes the customer data entry screen.

Image 19

When you fill data and hit submit, you will see the filled “Customer” object below.

Image 20

Lab 25:- Razor Layout

Introduction

Layouts are like master pages in ASP.NET Web form. Master pages give a standard look and feel for Web form views ( ASPX) while layout gives standard look and feel for razor views (CSHTML). In case you are new to Razor see Lab 12 MVC Razor view.

In this lab we will see how to implement Razor Layout.

Step 1: - Create Layout page

The first thing is we need to create a Layout page. So create a new MVC web application, go to the views folder, right click, add new item and select MVC Layout page template as shown in the below figure.

Image 21

In the MVC layout page we need to define the common structure which will be applied to all razor pages. You can see in the below layout page we have three sections Header, Body and Footer. Header and Footer are custom sections while “RenderBody” something which comes from MVC and displays the body content.

<div>
@RenderSection("Header")
@RenderBody()
@RenderSection("Footer")
</div> 

Step 2:- Create view and apply the layout

Now once we have created the layout the next thing is to apply that layout to a view. So right click on shared folders of the view and select razor view.

Image 22

To apply layout page select the “…” browse option as shown in the above figure and select layout page as shown in the below screen.

Image 23

Once the view is created the first line of code points out what layout the page is using. It looks something as shown in the below code.

HTML
@{Layout = "~/Views/Default1/_LayoutPage1.cshtml";}

So now the final thing in the view is to fill all sections. Footer and header section are custom sections so we need to use @section command followed by the section name and what we want to put in those sections. All the other text will be part of the body ( @RenderBody()).

HTML
This is body
@section  Footer{Copyright 2015-2016}
@section Header{Welcome to my site}

In simple words the mapping between the layout and the razor view code is as shown below.

Image 24

Step 3:- Create a controller and see your layout in action

Now that we are all set its time to create a controller and action to invoke the view. You should see something as shown below. You can see how the layout template is applied to the view.

Image 25

Lab 26 :- Custom Html Helper methods

Introduction

In day 1 we have talked about MVC Helper classes . It helps us to work with input controls in a more efficient manner. When you type ‘@Html.” in MVC razor view you get something like this in intellisense.

Image 26

Html helper method let us create Html input controls like Textbox, Radio button, Checkbox, Text Area easily and quickly.In this lab we will go one step ahead and create “Custom” helper method.

To create a custom HTML helper method we need to use extension methods. Extension method concept was introduced in .NET 3.5.

In case you are new to extension methods watch the below youtube video by www.questpond.com

http://www.youtube.com/watch?v=Iu7OrL6vCOw

Step 1 :- Create a MVC project with simple class file

Create a simple MVC project called CustomHtmlHelperDemo. Add a controller called HelperSample and an action called Index.Create a new Folder inside MVC project and call it ExtensionClasses.

Image 27

Step 2: Mark the class as Static and add methods

For extension method we need to mark the class as static.

public static class HelperExtension
{
}

In this class let’s create a new static method called “HelloWorldLabel” which will return a value of type MvcHtmlStringand accepting a parameter of type HtmlHelper.

Note: Make sure to add “this” keyword before declaring first parameter because our target is to create an extension method for HtmlHelper class.

publicstaticMvcHtmlStringHelloWorldLabel(this HtmlHelper helper)
{

}

Step 3: Use the Helper class.

The final step is to import “System.Web.Mvc.Html” namespace.We need to import this namespace because default TextBoxFor, TextAreaFor and other html helper extension methods are available inside this namespace. It is required only if we are going to use one of these extension method.

returnhelper.Label("Hello World");

Simply write following code in the view and say build , you may end up with an error as shown below.

Image 28

To resolve the above error simply put the using statement in the top of the view as follows

@using CustomHtmlHelperDemo.ExtensionClasses

Build the application, Press F5 and Test the application.

Image 29

What is for the Lastday?

My last day would be mainly on how to integrate Javascript framework’s ( Angular , KO) with MVC.

Final note, you can watch my c# and MVC training videos on various sections like WCF, Silver light, LINQ, WPF, Design patterns, Entity framework etc. By any chance do not miss my .NET and c# interview questions and answers book from www.questpond.com .

Are you completely new to MVC?

In case you are completely a fresher I will suggest to start with the below 4 videos which are 10 minutes approximately so that you can come to MVC quickly.

Lab 1:- A simple Hello world ASP.NET MVC application.

Image 30

Lab 2:- In this Lab we will see how we can share data between controller and the view using view data.

Image 31

Lab 3 :- In this lab we will create a simple customer model, flourish the same with some data and display the same in a view.

Image 32

Lab 4 :- In this lab we will create a simple customer data entry screen with some validation on the view.

Image 33

Start with MVC 5

In case you want to start with MVC 5 start with the below video Learn MVC 5 in 2 days.

Image 34

Do not miss MVC interview questions with answers

Every lab I advance in this 7 day series I am also updating a separate article which discusses about important MVC interview questions which are asked during interviews. Till now I have collected 60 important questions with precise answers you can have a look at the same from http://www.codeproject.com/Articles/556995/Model-view-controller-MVC-Interview-questions-and

For further reading do watch the below interview preparation videos and step by step video series.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)