Click here to Skip to main content
15,892,746 members
Articles / Web Development / ASP.NET

All ASP.NET MVC 3 Features

Rate me:
Please Sign up or sign in to vote.
4.50/5 (4 votes)
6 Dec 2013CPOL7 min read 23.6K   4  
All ASP.NET MVC 3 features

Introduction

MVC 3 can be installed in Visual Studio 2010 from here.

There are many new features that have been introduced in MCV 3 with respect to project templates, controller, model and view.

MVC 3 has been officially launched on 09-Nov-2010.

All MVC 3 Features

MVC 3 features have been categorised as below:

  1. MVC Project Templates
  2. View
  3. Controller
  4. Model

I. MVC Project Templates

1. New Intranet Project Template

New “Intranet Application” project template has been added in MVC 3. This project template will only remove the account controller and add the Windows authentication.

2. Extensible Scaffolding with MvcScaffold integration

Scaffold template will automatically generate the base code which will be fast development for demo (: and we can edit based on our requirement.

3. HTML 5 Project Templates

When we create a new project, at that time, we have an option of checkbox to support the HTML 5 to the project.

Image 1

4. Extensible "New Project" Dialog Box

When we create a new project with MVC 3, then we have options with project template for view engine and unit test project template.

Image 2

II. VIEW

1. Razor View Engine

Razor view Engine has been introduced in ASP.NET MVC 3 with Visual Studio 2010. This is most compatible and suggested engine with MVC framework.

What is Razor View: Razor is markup syntax that will embed the server base code into web page. Razor is not a programming language. This is a server side markup language. With server base code, we can create the dynamic web page. If any dynamic page is requested from the browser, then server based code will get executed inside the web page and complete HTML version will return to the browser.

Advantages

  • This provides optimize syntax to generate the HTML by code-focused template approach, with this approach minimal transaction between code and HTML. It also reduces the number of characters and keystrokes.
  • Razor syntax is clean and concise.
  • Unit testable without running the application or web server.
  • Having “Layouts” page same like master make in ASP.NET.
  • Razor having IntelliSense and code colorization with Visual Studio.
  • Easy to learn as this is based on C# and Visual Basic.
  • This supports TDD development as Razor does not depend on System.Web.UI.Page class.
  • Razor prevents the XSS attacks by default as it encodes the script or html tag “< >” before rendering to view.

Syntax: Razor uses “@” character for the code block, this does not require to explicitly close the code block.

Example

Hello World
Today DateTime: @DateTime.Now
2. Support for Multiple View Engines

MVC 3 framework allows multiple view engines in the same project. When creating a new project, we have to select the default view engine, when we are adding new view, we can select different view such as “ASPX” or any other open source Spark, NHaml, or NDjango.

3. Partial-Page Output Caching

From version MVC 1, page caching been supported. MVC 3 has been included the partial page caching which will cache the region or fragments of a response.

4. Granular Control over Request Validation

In ASP.NET MVC, there is a built-in request validator that will automatically protect XSS and HTML injection attacks. Sometimes, we need to allow the HTML content, e.g. blog submit, CMS system or content submit through HTML editor, this can be allowed by MVC 3.

5. New Overloads for "Html.LabelFor" and "Html.LabelForModel"

New overload method been added in MVC 3 as “@Html.LabelFor” and “@Html.LabelForModel”, with this we can specify the label text or override the text.

6. Client-Side Validation Enabled by Default

In earlier version of MVC, we need to explicitly call Html.EnableClientValidation in view to enable client side validation. From MVC 3, by default client side validation is enabled. Client side validation completely uses JQuery and JQueryValidation library.

III. Controller

1. Global Action Filters

MVC 2 introduces the action filter which actually applies the pre and post action behaviour to the action method or controller. In MVC 3, global action filter has been introduced which actually applies pre and post action behaviour to the application level that means one place we can define the action filter and that will work for all the action methods.

Example

Suppose we have to do the authentication for the application so what we have to do the authorization for all the action method. Now, in MVC 3, we have to do in one place that will work for complete application. Here is the way to do it:

Open Global.Asax and do the modification as below:

C#
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
    filters.Add(new AuthorizeAttribute()); //this is the line for global filter
    //filters.Add(new HandleErrorAttribute());
}
        
protected void Application_Start()
{
    AreaRegistration.RegisterAllAreas();

    RegisterGlobalFilters(GlobalFilters.Filters); //this is the line for global filter
    RegisterRoutes(RouteTable.Routes);
}    
2. New "ViewBag" Property

ViewBag is a dynamic property which can be used to pass data from controller to view. This will be late binding same as ViewData. This will get and set the value at run time as this is dynamic property, internally use the ViewData object as name/Value pair.

Here is the simple syntax:

C#
Controller:
ViewBag.Message="this is view bag";

View:
@ViewBag.Message     
3. New "ActionResult" Types

Below are the new action result type and corresponding helper method has been added in the MVC 3:

  • HttpNotFoundResult: This will return 404 error code to client.
    • Action result type: "HttpNotFoundResult"
    • Helper method: "HttpNotFound"
    C#
    public ActionResult PageNotFound()
    {
        return HttpNotFound();
    }
    public ActionResult Index()
    {
        ViewBag.Message = "Welcome to ASP.NET MVC!";
    
        var result = new HttpNotFoundResult();
        // var result = new HttpNotFoundResult("Page not found"); //we can pass the parameter also
        return result;
        //return View();
    }    
  • RedirectResult: Redirect result added three new helper methods for permanent redirect as below. All will give the status code to client 301.
    • RedirectPermanent
    • RedirectToRoutePermanent
    • RedirectToActionPermanent
  • HttpStatusCodeResult: Returns a user defined status code to the browser.
    C#
    public ActionResult SpecificStatusCode()
    {
        var objProduct = new Product();
    
        if (objProduct == null)
            return new HttpStatusCodeResult(418);
    
        return View();
    }
4. Remote Validator

MVC 3 added a new attribute RemoteAttribute class that will enable us to take advantage of JQuery validation plugin with a custom class method for the validation from server side code.

Example: Suppose we have a product class and would like to check with product ID, if product ID already exists in the database.

C#
Modal code:

[Remote("IsProductExist","productid")]
public int ID { get; set; }
public string Name { get; set; }
    
Controller code:

public bool IsProductExist(int productid)
{
    if (productid == null) //just give the proper object condition 
        return false;
    else
        return true;
}
5. JSON Binding Support

MVC 3 by default enables us to send and receive the JSON object data.

6. Dependency Injection Improvements

MVC 3 provides the better support for the dependency injection. With DI, we will have n number of benefits which will be out of scope here. Common Service Locator library and any DI container will be supported by MVC 3 that support IServiceLocator interface. Also supports IDependencyResolver interface that will make the DI to integration easily.

7. Sessionless Controller Support

MVC 3 supports the session less controlled, also support read or read/write option.

IV. Model

1. JavaScript and Ajax Improvements

MVC 3 by default uses unobtrusive framework for client side JavaScript validation. With this approach, we have no need to inject the JavaScript validation code to the HTML controls. This by default uses the JQueryValidation plugin to validate the data.

Example

C#
public class ChangePasswordModel
{
    [Required]
    public string NewPassword { get; set; }

    [Required]
    public string ConfirmPassword { get; set; }
}   

In the above code, when the text boxes will be created with the above model, classPassword and confirm password will be required field. Go through the URL for the complete details:

2. New "AdditionalMetadataAttribute" Class:

AdditionalMetadataAttribute will provide special feature to the modal view data. Suppose we have to provide specific role user to view the modal data attribute, then we can use the AdditionalMetadataAttribute.

Example

C#
[AdditionalMetadata("Admin", true)]
public int ProductCode { get; set; }

In the above code “ProductCode” attribute will be visible to the admin only.

3. "DataAnnotations" Metadata Attributes

DataAnnotation metadata been supported by MVC 3 such as Displayattribute.

4. "ValidationAttribute" Class

In .NET Framework 4, ValidationAttribute was enhanced to support new method IsValid overload which provides more information about the current validation context. This provides very enhanced way of doing validation based on the model property.

Example

C#
 public class RegisterModel
{
    [Required]
    public string UserName { get; set; }

    [Required]
    public string Email { get; set; }

    [Required]
    [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", <br />            MinimumLength = 6)]
    public string Password { get; set; }

    [Display(Name = "Confirm password")]
    [Compare("Password",
    ErrorMessage = "The password and confirmation password do not match.")]
    public string ConfirmPassword { get; set; }
}
5. Validation Interfaces
  • IValidatableObject: This interface will do the validation at the model level and generate the error messages which define at the model attributes. In MVC 3, when model binds to the view then IValidatableObject generates the error messages and binds to the HTML form helpers.
  • IClientValidatable: This interface will discover at runtime that client side validations is enabled or not. This interface is designed to support the various validation frameworks.

Summary

I have tried to explain all the features available in the ASP.NET MVC 3. Hope you have enjoyed reading the entire topic. Please provide your vote suggestion and feedback... to encourage me to write more blogs.

License

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


Written By
Software Developer (Senior) Epicor Software
India India
16+ years of experience in designing and developing Microsoft technologies applications.
My expertise skills are ASP.Net,MVC 3/4,MVC 4 WEB API, C#, WCF, REST, UML, Design Pattern,Angular, Node, Type script and SQL server.

You can reach me @ mdafazal@gmail.com

Comments and Discussions

 
-- There are no messages in this forum --