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
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.
http://www.codeproject.com/Articles/207797/Learn-MVC-Model-view-controller-Step-by-Step-in-7
http://www.codeproject.com/Articles/259560/Learn-MVC-Model-view-controller-Step-by-Step-in-7
http://www.codeproject.com/Articles/375182/Learn-MVC-Model-View-Controller-Step-by-Step-in-7
http://www.codeproject.com/Articles/375182/Learn-MVC-Model-View-Controller-Step-by-Step-in-7
http://www.codeproject.com/Articles/724559/Learn-MVC-Model-view-controller-Step-by-Step-in-7
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.
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.
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.
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();”.
publicclassHomeController : Controller
{
publicActionResult Index()
{
return View();
}
}
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.
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/
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.
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.
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.
protectedvoid Application_Start()
{
DisplayModeProvider.Instance.Modes.
Insert(0, newDefaultDisplayMode("Android")
{
ContextCondition = (context => context.
GetOverriddenUserAgent().IndexOf("Android",
StringComparison.OrdinalIgnoreCase) >= 0)
});
}
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.
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).
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.
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.
Give “app name”, ”category” and hit the “create App” button as shown in the below figure.
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.
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”.
Once the project is created open the “AuthoConfig.cs” from the “App_start” folder.
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.
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.
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.
It open’s one more dialog box , choose website and click Add.
In the URL give your local host URL with the port number as shown in the below figure.
That’s it you are all set , now the run the application and click log in.
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.
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.
<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.
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.
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.
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”.
The first step is to create “EnterCustomer.aspx” view which will take “Customer” data.
<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.
publicclassCustomerController : Controller
{
publicActionResult EnterCustomer()
{
return View();
}
}
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.
publicclassCustomer
{
publicstring CustomerCode { get; set; }
publicstring CustomerName { get; set; }
}
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.
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
};
}
}
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.
publicclassCustomerController : Controller
{
publicActionResult SubmitCustomer([ModelBinder(typeof(CustomerBinder))]Customer obj)
{
return View("DisplayCustomer");
}
}
So now hit the action (“EnterCustomer”) which invokes the customer data entry screen.
When you fill data and hit submit, you will see the filled “Customer” object below.
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.
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.
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>
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.
To apply layout page select the “…” browse option as shown in the above figure and select layout page as shown in the below screen.
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.
@{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()).
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.
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.
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.
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
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.
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)
{
}
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.
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.
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 .
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.
Lab 2:- In this Lab we will see how we can share data between controller and the view using view data.
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.
Lab 4 :- In this lab we will create a simple customer data entry screen with some validation on the view.
Start with MVC 5
In case you want to start with MVC 5 start with the below video Learn MVC 5 in 2 days.
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.