|
.NET
MVC FRAMEWORK CONCEPTS
|
MVC is a new web application framework from
Microsoft. MVC stands for Model-View-Controller, a pattern that’s becoming
increasingly popular with web development frameworks. ASP.NET MVC is an
alternative and a complement to Web Forms, which means you won’t be dealing with pages
and controls, postbacks or view state, or complicated asp.net event life
cycles.
Basically, MVC is a framework methodology that divides an
application's implementation into three component roles: models, views, and
controllers.
MVC Web Application Advantages
1.
Separation
In MVC
the application is divided to Model, View and Controller parts which make it
easier to manage the application complexity.
2.
TDD
The MVC
framework brings better support to test-driven
development.
3.
Extensible and pluggable
MVC
framework components were designed to be pluggable and extensible and therefore
can be replaced or customized easier then Web Forms.
4.
Full control over
application behavior
MVC
framework doesn’t use View State or
server based forms like Web Forms. This gives the application developer more
control over the behaviors of the application and also reduces the bandwidth of
requests to the server.
5.
ASP.NET features are
supported
MVC
framework is built on top of ASP.NET and therefore can use most of the features
that ASP.NET include such as the providers architecture,
authentication and authorization scenarios, membership and roles, caching, session and more.
6.
URL routing mechanism
MVC
framework supports a powerful URL routing mechanism that helps to build a more
comprehensible and searchable URLs in your application. This mechanism helps to
the application to be more addressable from the eyes of search engines and
clients and can help in search engine optimization.
The
ASP.NET MVC simplifies the complex parts of ASP.net Web Forms without any
compromise of the power and flexibility of ASP.NET platform. ASP.net MVC
implements Model-View-Controller UI pattern for web application development
that lets you allows to develop applications in a loosely couples manner. MVC
pattern is separating the application in three parts- Model, View and
Controller.
What is the difference between each
version of MVC?
MVC 2
|
MVC 3
|
MVC 4
|
·
Client-side validation
·
Templated Helpers Areas
·
Asynchronous Controllers
·
Html.ValidationSummary Helper
Method
·
DefaultValueAttribute in Action-Method
·
Parameters binding
·
Binary data with Model Binders
·
DataAnnotations Attributes
·
Model-Validator Providers
·
New RequireHttpsAttributeAction Filter
·
Templated Helpers
·
Display Model-Level Errors
|
·
Razor
·
Readymade project templates
·
HTML 5 enabled templates
·
Support for Multiple View Engines, JavaScript, and AJAX
·
Model Validation Improvements
|
·
ASP.NET Web API
·
Refreshed and modernized default project templates.
·
New mobile project template.
·
Many new features to support mobile apps
·
Enhanced support for asynchronous methods
·
Asynchronous Handler & Module
·
Display Mode
·
Bootstrap
Layout
|
Model
1.
Model is basically c#
.net classes.
2. Model is accessible by both View & controller.
3.
Model can be used to
pass data from controller to view.
- A view can
use model to display data in page.
What is a View?
1. View is an ASPX or .cshtml or .vbhtml page without having a code behind
file
2. All page specific HTML
generation and formatting can be done inside view
3. One can use Inline code (server
tags ) to develop dynamic pages
4. A request to view (ASPX page/.cshtml) can be made
only from a controller’s action method
What is a Controller?
1. Controller is basically a C# or VB.NET
class which inherits system.mvc.controller
2. Controller is a heart of the entire MVC
architecture
3. Inside Controller’s class action methods can be
implemented which are responsible for responding to browser OR calling views.
4. Controller can access and use model class to pass data to views
5. Controller uses ViewData to pass any data to view
What is ViewModel ?
. A View model represents data that you want to have displayed on your view page.
. ViewModel put only those fields/data that you want to display on the view page
. ViewModel put only those fields/data that you want to display on the view page
Why We Use ViewModel
1. If you need to pass more than
one thing to a strongly-typed view (which is best practice),
you
will generally want to create a separate class to do so.
2. This allows you to validate your
ViewModel differently than your domain model for
attribute-based validation scenarios
3. Can be used to help shape and format
data.
e.g: need a date or money value formatted
a particular way?
ViewModel is the best place to do it.
4. ViewModels are generally a more flexible way to access
multiple data sources than domain models.
5. The use of a ViewModel can make the interaction between model
and view more simple
Best Practices When Using ViewModels
1. Put only data that you'll render (use in View) in the ViewModel
2. The View should direct the properties of the ViewModel, this way
it fits better for rendering
and maintenance
What are partial views in MVC?
Partial view is a reusable view (like a user control) which can be embedded inside
other view. For example let’s say all your pages of your site have a standard
structure with left menu, header, and footer as shown in the image below.
For every page you would like to reuse the left menu,
header, and footer controls. So you can go and create partial views for each of
these items and then you call that partial view in the main view.
What are Strongly Typed views in MVC?
A Strongly Typed view means it has a ViewModel
associated to it that the controller is passing to it and all the elements in
that View can use those ViewModel properties
How did you create a partial view and consume it?
When you add a view to your project you need to check
the “Create partial view” check box.
Once the partial view is created you can then call
the partial view in the main view using the
Html.RenderPartialmethod as shown in the below code snippet:<body>
<div>
<% Html.RenderPartial("MyView"); %>
</div>
</body>
How can we do validations in MVC?
One of the easiest
ways of doing validation in MVC is by using data annotations. Data annotations are nothing but attributes which can be applied on model properties. For example, in the
below code snippet we have a simple
Customer class with a property customercode.
This
CustomerCode property is tagged with a Required data annotation attribute. In other words if this
model is not provided customer code, it will not accept it.public class Customer
{
[Required(ErrorMessage="Customer code is required")]
public string CustomerCode
{
set;
get;
}
}
MVC Arcitecture & Page Lifecycle
What is System.Web.Mvc namespace?
This namespace contains classes
and interfaces that support the MVC pattern for ASP.NET Web applications. This
namespace includes classes that represent controllers, controller, factories,
action results, views, partial views, and model binders.
What are the default Top level
directories created when adding MVC4 application?
Default Top
level Directories are:
DIRECTORY PURPOSE
/Controllers To put Controller classes that handle
URL requests
/Models To put classes that represent
and manipulate data and business objects
/Views To put UI template files
that are responsible for rendering output like HTML.
/Scripts To put JavaScript library
files and scripts (.js)
/Images To put images used in your
site
/Content To put CSS and other site content,
other than scripts and images
/Filters To put filter code.
/App_Data To store data files you want to
read/write
/App_Start To put configuration code for
features like Routing, Bundling, Web API.
What are HTML
helpers in MVC?
HTML
helpers help you to render HTML controls in the view. For instance if you want
to display a HTML textbox on the view , below is the HTML helper code.
<%= Html.TextBox("LastName") %>
Html.TextBoxFor(m => m.CustomerCode)
What is the
difference between “HTML.TextBox” vs “HTML.TextBoxFor”?
Both
of them provide the same HTML output, “HTML.TextBoxFor” is strongly typed while “HTML.TextBox” isn’t. Below is a simple HTML
code which just creates a simple textbox with “CustomerCode” as name.
How can we navigate from one view to
another using a hyperlink?
<%= Html.ActionLink("Home","Gotohome") %>
State Management in MVC
ViewData
1.
ViewData is used to pass data from controller to view
2.
It is derived from ViewDataDictionary class
3.
It is available for the current request only
4.
Requires typecasting for complex data type and checks for
null values to avoid error
5.
If redirection occurs, then its value becomes null
ViewData["Name"] = "Hi";
@ViewData["Name"]
ViewData["Name"] = "Hi";
@ViewData["Name"]
ViewBag
1.
ViewBag is also used to pass data from the controller
to the respective view
2.
ViewBag is a dynamic property that takes advantage of
the new dynamic features in C# 4.0
3.
It is also available for the current request only
4.
If redirection occurs, then its value becomes null
5.
Doesn’t require typecasting for complex data type
How can
you define a dynamic property with the help of viewbag in ASP.NET MVC?
Assign a key name with syntax,
ViewBag.[Key]=[
Value] and value using equal to operator.
For example, you need to assign list of
students to the dynamic Students property
of ViewBag.
List<string> students = new
List<string>();
countries.Add("Girija");
countries.Add("Mohanty");
ViewBag.Students = students;
//Students is a dynamic property associated
with ViewBag.
TempData
1.
TempData is derived from TempDataDictionary class
2. TempData is also a dictionary derived from TempDataDictionary class and stored in sort live session and it is a string key and object value.
2. TempData is also a dictionary derived from TempDataDictionary class and stored in sort live session and it is a string key and object value.
3.
TempData is used to pass data from the current request
to the next request
4.
It keeps the information for the time of an HTTP Request.
This means only from one page to another. It helps to maintain the data when we
move from one controller to another controller or from one action to another
action
5.
It requires typecasting for complex data type and checks
for null values to avoid error. Generally, it is used to store only one time
messages like the error messages and validation messages
Example :
Model
namespace MvcApplication2.Models
{
public class Customer
{
public string UserName { get; set; }
}
}
Controller Code
Right-click
on the "Controller" folder and add a controller with the name "Customer Controller" and add the following code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MvcApplication2.Models;
namespace MvcApplication2.Controllers
{
public class CustomerController : Controller
{
//
// GET: /Default/
public ActionResult Index()
{
var customerName = new Customer
{
UserName = "Girija",
};
ViewBag.Customer = customerName; // Defines ViewBag
ViewData["ViewCustomer"] = customerName; // Defines ViewData
TempData["TempCustomer"] = customerName; // Defines TempData
return View();
}
In View Page
@model MvcApplication2.Models.Customer
@{
var ViewBagTest = (ViewBag.Customer as MvcApplication2.Models.Customer).UserName;
var ViewDataTest = (ViewData["ViewCustomer"] as MvcApplication2.Models.Customer).UserName;
var TempDataTest = (TempData["TempCustomer"] as MvcApplication2.Models.Customer).UserName;
<div>
<h1>@ViewBagTest</h1>
<h2>@ViewDataTest</h2>
<h3>@TempDataTest</h3>
</div>
}
Next Request
(Redirection) Code
Now see the example of
a Next Request to understand the
TempData object. In the Next Request (Redirection), the TempData value does
not become null. But in the case of ViewData and ViewBag the value
becomes null. Now change the CustomerController code to make a redirection (Next Request).
Now the
CustomerController Code is as the following:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MvcApplication2.Models;
namespace MvcApplication2.Controllers
{
public class CustomerController : Controller
{
//
// GET: /Default/
public ActionResult Index()
{
var customerName = new Customer
{
UserName = "Rohatash",
};
ViewBag.Customer =
customerName; // Defines ViewBag
ViewData["ViewCustomer"] = customerName; // Defines ViewData
TempData["TempCustomer"] = customerName; // Defines TempData
return RedirectToAction("TempDataTest");
}
public ActionResult TempDataTest()
{
String ViewBagTest = ViewBag.Customer; // After the redirect, ViewBag contains null
value.
String ViewDataTest = (string)ViewData["ViewCustomer"]; // After the redirect,
ViewData also contains null value.
String TempDataTest = TempData["TempCustomer"].ToString(); //After the redirect,
Only TempData survives a redirect
return View("Index");
}
}
}
Below is a summary table which shows the different mechanisms
for persistence.
Maintains data between
|
ViewData/ViewBag
|
TempData
|
Hidden fields
|
Session
|
Controller to Controller
|
No
|
Yes
|
No
|
Yes
|
Controller to View
|
Yes
|
Yes
|
No
|
Yes
|
View to Controller
|
No
|
No
|
Yes
|
Yes
|
ViewData VS
ViewBag VS TempData
ViewData
|
ViewBag
|
TempData
|
It is Key-Value Dictionary collection
|
It is a type object
|
It is Key-Value Dictionary collection
|
ViewData is a dictionary object and it is
property of ControllerBase class
|
ViewBag is Dynamic property of
ControllerBase class.
|
TempData is a dictionary object and it is
property of controllerBase class.
|
ViewData is Faster than ViewBag
|
ViewBag is slower than ViewData
|
NA
|
ViewData is introduced in MVC 1.0 and
available in MVC 1.0 and above
|
ViewBag is introduced in MVC 3.0 and
available in MVC 3.0 and above
|
TempData is also introduced in MVC1.0 and
available in MVC 1.0 and above.
|
ViewData is also work with .net
framework 3.5 and above
|
ViewBag is only work with .net
framework 4.0 and above
|
TempData is also work with .net
framework 3.5 and above
|
Type Conversion code is required while
enumerating
|
In depth, ViewBag is used dynamic, so there
is no need to type conversion while enumerating.
|
Type Conversion code is required while
enumerating
|
It value become null if redirection is
occurred.
|
Same as ViewData
|
TempData is used to pass data between two
consecutive requests.
|
It lies only during the current request.
|
Same as ViewData
|
TempData is only work during the current
and subsequent request
|
What is Display Mode in MVC ?
MVC
4 has introduced display mode feature which will simplify how to implement
different versions of view for different devices
Display mode displays views
depending on the device the user has logged in with. So we can create different
views for different devices and display mode will handle the rest.
In other words, suppose we have a web page content
which is designed for the desktop version of browser but in mobile browser or
any other device browser contents are not properly readable, now in this case
we want to create a different view for different devices.
Earlier also, we were implementing compatibility
issues by our own framework and with more coding. MVC 4 very much simplified
this to implement.
Generic Implementation for Mobile Device View
Please follow the below steps to implement the
generic mobile device view.
Step 1: Create a layout view for the mobile device. To
quickly implement, copy “Views\Shared\_Layout.cshtml” paste to the same
location and modify the layout file name as “\_Layout.Mobile.cshtml” (“Views\Shared\_Layout.Mobile.cshtml”).
Step 2: Modify the “\_Layout.Mobile.cshtml”
page header text to identify that layout view run from mobile version.
Step 3: Copy the “Views\Home\index.cshtml”
and paste to the same location and modify the file name as “Views\Home\index.Mobile.cshtml”.
Step 4: Modify the “\Index.Mobile.cshtml”
page header text to identify that index view run from mobile version.
That’s all. If there is any view we have to configure from
mobile device, then follow the above process.
Run and Test from IE Browser
1. Desktop View
Press F5 and the result will be desktop version of
view, as below. We can see layout and index page heading is showing as “Desktop”
2. Mobile View
Do the IE setting changes as above explained. In IE, Press F12
--> tools --> change user agent string --> ”IE10 for Windows Phone 8”.
Refresh the page, now mobile view override and invoked.
Mobile view in Windows mobile 7:
IV. Specific Browser or Device
View
Above, we have created a generic mobile view so any
time from mobile or iPad browser will get access then mobile version of view
will be invoked. Now the case will be, we want to create a view for iPhone
browser or any other specific device, this is also supported by MVC 4 feature
by just doing couple of configurations.
Below is taken an example for “iPad” as in my browser that is installed:
Step 1: Open Global.Asax and add the below line of code to the “
Application_Start()” method also add the namespace as “using System.Web.WebPages;”.DisplayModeProvider.Instance.Modes.Insert(0, new DefaultDisplayMode("iPad")
{
ContextCondition = (context => context.GetOverriddenUserAgent().IndexOf
("iPad", StringComparison.OrdinalIgnoreCase) >= 0)
});
Step 2: Create a layout view for the iPad. To quickly
implement, copy “Views\Shared\_Layout.cshtml” paste to the same
location and modify the layout file name as “\_Layout.iPad.cshtml” (“Views\Shared\_Layout.iPad.cshtml”).
Step 3: Modify the “\_Layout.iPad.cshtml” page header text to identify
that layout view run from mobile version.
Step 4:
Copy the “Views\Home\index.cshtml”
and paste to the same location and modify the file name as “Views\Home\index.iPad.cshtml”
.
Step 5:
Modify the “\Index.iPad.cshtml”
page header text to identify that index view run from mobile version.
That’s all if any view we have to configure from iPad
device, then follow the above process.
Run and Test from IE Browser
Mobile View
Do the IE setting changes as above explained. In IE,
Press F12 --> tools --> change user agent string --> ”iPad”.
Refresh the page, now iPad view override and invoked.
What are the type of scaffolding Templets?
SCAFFOLD DESCRIPTION
Empty Creates empty view. Only the
model type is specified using the model syntax.
Create Creates a view with a form
for creating new instances of the model.
Generates a label
and input field for each property of the model type.
Delete Creates a view with a form
for deleting existing instances of the model.
Displays a label
and the current value for each property of the model.
Details Creates a view that displays
a label and the value for each property of the
model type.
Edit Creates a view with a
form for editing existing instances of the model.
Generates a label
and input fi eld for each property of the model type.
List Creates a view with a
table of model instances. Generates a column
for each property
of the model type. Make sure to pass an
Enumerable<YourModelType>
to this view from your action method.
The view also
contains links to actions for performing the create/edit/delete operations.
What
is bundling and minification in MVC?
Bundling and minification helps us improve request load times of a page thus
increasing performance.
Web
projects always need CSS and script files. Bundling helps us combine multiple JavaScript and CSS files
in to a single entity thus
minimizing multiple requests in to a single request.
how to
implement bundling in MVC?
Open BundleConfig.cs from the App_Start folder.
public class BundleConfig
{
public static void RegisterBundles(BundleCollection bundles)
{
bundles.Add(new ScriptBundle("~/Scripts/MyScripts").Include( "~/Scripts/*.js"));
BundleTable.EnableOptimizations = true;
}
}
Explain Areas in MVC?
Areas
help you to group functionalities in to independent modules thus making your
project more organized. For example in the below MVC project we have four
controller classes and as time passes by if more controller classes are added
it will be difficult to manage. In bigger projects you will end up with 100’s
of controller classes making life hell for maintenance.
Filters
in MVC?
MVC provides a simple way to inject your
piece of code or logic either before or after an action is executed.
This
is achieved by decorating the controllers or actions with ASP.NET MVC
attributes or custom attributes.
An
attribute or custom attribute implements the ASP.NET MVC filters (filter
interface) and can contain your piece of code or logic. You can make your own
custom filters or attributes either by implementing ASP.NET MVC filter
interface or by inheriting and overriding methods of ASP.NET MVC filter
attribute class if available.
Typically,
Filters are used to perform the following common functionalities in your
ASP.NET MVC application.
1.
Custom Authentication
2.
Custom Authorization(User based or Role based)
3.
Error handling or logging
4.
User Activity Logging
5.
Data Caching
6.
Data Compression
Types of Filters
MVC
framework provides five types of filters.
1. Authentication filters (New in ASP.NET MVC5)
2. Authorization filters
3. Action filters
4. Result filters
5. Exception filters
Authentication Filters
This filter is introduced with ASP.NET MVC5. The
IAuthenticationFilter interface is used to create CustomAuthentication filter.
The definition of this interface is given below-
public interface IAuthenticationFilter
{
void OnAuthentication(AuthenticationContext filterContext);
void OnAuthenticationChallenge(AuthenticationChallengeContext filterContext);
}
You
can create your CustomAuthentication filter attribute by implementing
IAuthenticationFilter as shown below-
public class CustomAuthenticationAttribute : ActionFilterAttribute, IAuthenticationFilter
{
public void OnAuthentication(AuthenticationContext filterContext)
{
//Logic for authenticating a user
}
//Runs after the OnAuthentication method
public void OnAuthenticationChallenge(AuthenticationChallengeContext filterContext)
{
//TODO: Additional tasks on the request
}
}
Authorization Filters
The ASP.NET MVC
Authorize filter attribute implements the IAuthorizationFilter interface. The
definition of this interface is given below-
1. public interface IAuthorizationFilter
2. {
3. void OnAuthorization(AuthorizationContext filterContext);
4. }
The AuthorizeAttribute
class provides the following methods to override in the CustomAuthorize
attribute class.
1. public class AuthorizeAttribute : FilterAttribute, IAuthorizationFilter
2. {
3. protected virtual bool AuthorizeCore(HttpContextBase httpContext);
4. protected virtual void HandleUnauthorizedRequest(AuthorizationContext filterContext);
5. public virtual void OnAuthorization(AuthorizationContext filterContext);
6. protected virtual HttpValidationStatus OnCacheAuthorization(HttpContextBase httpContext);
7. }
In this way you can
make your CustomAuthorize filter attribute either by implementing
IAuthorizationFilter interface or by inheriting and overriding above methods of
AuthorizeAttribute class.
Action Filters
Action filters are executed before or
after an action is executed. The IActionFilter
interface is used to create an Action Filter which provides two methods
OnActionExecuting and OnActionExecuted which will be executed before or after
an action is executed respectively.
1. public interface IActionFilter
2. {
3. void OnActionExecuting(ActionExecutingContext filterContext);
4. void OnActionExecuted(ActionExecutedContext filterContext);
5. }
Result Filters
Result filters are executed
before or after generating the result for an action.
The Action Result type can be ViewResult, PartialViewResult,
RedirectToRouteResult, RedirectResult, ContentResult, JsonResult, FileResult
and EmptyResult which derives from the ActionResult class. Result filters are
called after the Action filters. The IResultFilter interface is used to create
an Result Filter which provides two methods OnResultExecuting and
OnResultExecuted which will be executed before or after generating the result
for an action respectively.
1. public interface IResultFilter
2. {
3. void OnResultExecuted(ResultExecutedContext filterContext);
4. void OnResultExecuting(ResultExecutingContext filterContext);
5. }
Exception Filters
Exception filters are
executed when exception occurs during the actions execution or filters
execution. The
IExceptionFilter interface is used to create an Exception Filter which provides
OnException method which will be executed when exception occurs during the
actions execution or filters execution.
1. public interface IExceptionFilter
2. {
3. void OnException(ExceptionContext filterContext);
4. }
ASP.NET MVC HandleErrorAttribute filter is an Exception filter
which implements IExceptionFilter. When HandleErrorAttribute filter receives
the exception it returns an Error view located in the Views/Shared folder of
your ASP.NET MVC application.
Order of Filter Execution
All ASP.NET MVC filter are executed in an order. The correct
order of execution is given below:
1. Authentication filters
2. Authorization filters
3. Action filters
4. Result filters
Configuring Filters
You can configure your
own custom filter into your application at following three levels:
1.
Global level
By registering your filter into
Application_Start event of Global.asax.cs file with the help of FilterConfig
class.
1. protected void Application_Start()
2. {
3. FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
4. }
2.
Controller level
By putting your filter on the top of the
controller name as shown below-
1. [Authorize(Roles="Admin")]
2. public class AdminController : Controller
3. {
4. //
5. }
3.
Action level
By putting your filter on the top of the
action name as shown below-
1. public class UserController : Controller
2. {
3. [Authorize(Users="User1,User2")]
4. public ActionResult LinkLogin(string provider)
5. {
6. // TODO:
7. return View();
8. }
9. }
Action
Result
Action
Result is a return type of a controller in MVC.
Action
Method helps to return model to view, File Stream and also another controller.
Action
Result classes are derived from Action Result Abstract class.
ViewResult:
The view result class inherits from the abstract class “viewResultBase” and
used to render a view.
Public
ViewResult ViewSomething()
{
Return
view(“”);
}
PartialViewResult:
Render a partial view .
RedirectResult: It perform an HTTP redirect to given result.
This class
is inherits from “ActionResult” Abstract Class.
ContentResult:
Used to return an action as a plain text. This class inherits from
“ActionResult” Abstract Class.
JSonResult:
Action Method on controller returns JsonResult.
EmptyResult : Return a null result
RedirectToRoutResult: Redirect to another action method
[NonAction]
public EmptyResult Getemployee1()
{
List<Employee> EmplopyeeInfo =
GetApiResponse<List<Employee>>("Employee", "Getemployee");
return
Json(new { data = EmplopyeeInfo }, JsonRequestBehavior.AllowGet);
}
MVC 4 calling async method in controller.
System.Web.Mvc.Async namespace
contains classes and interfaces that support asynchronous actions in an ASP.NET
MVC application
System.Web.Mvc.Async namespace
contains classes and interfaces that support asynchronous actions in an ASP.NET
MVC application
public MyController : AsyncController
{
public ActionResult DoSomething()
{
CallSomeMethodWhichDoesAsyncOperations();
return Json(new { success = successful }, JsonRequestBehavior.AllowGet);
}
}
public MyController : Controller
{
public async Task<ActionResult> DoSomething()
{
await Task.Run(() => CallSomeMethodWhichDoesAsyncOperations());
return Json(new { success = successful }, JsonRequestBehavior.AllowGet);
}
}
View in Page Inspector
Thank You
Girija Mohanty
Sr. Software Engineer


No comments:
Post a Comment