Friday, August 3, 2012

MVC3 Razor Important Points & Tips


ASP.NET MVC 3


ASP.NET MVC 3 is a framework for building scalable, standards-based web applications using well-established design patterns and the power of ASP.NET and the .NET Framework



HTML 5 Project Templates

The New Project dialog includes a checkbox enable HTML 5 versions of project templates. These templates leverage Modernizr 1.7 to provide compatibility support for HTML 5 and CSS 3 in down-level browsers.
The Razor View Engine
ASP.NET MVC 3 comes with a new view engine named Razor that offers the following benefits:
  • Razor syntax is clean and concise, requiring a minimum number of keystrokes.
  • Razor is easy to learn, in part because it's based on existing languages like C# and Visual Basic.
  • Visual Studio includes IntelliSense and code colorization for Razor syntax.
  • Razor views can be unit tested without requiring that you run the application or launch a web server.
Some new Razor features include the following:
  • @model syntax for specifying the type being passed to the view.
  • @* *@ comment syntax.
  • The ability to specify defaults (such as layoutpage) once for an entire site.
  • The Html.Raw method for displaying text without HTML-encoding it.
  • Support for sharing code among multiple views (_viewstart.cshtml or _viewstart.vbhtml files).
Razor also includes new HTML helpers, such as the following:
  • Chart. Renders a chart, offering the same features as the chart control in ASP.NET 4.
  • WebGrid. Renders a data grid, complete with paging and sorting functionality.
  • Crypto. Uses hashing algorithms to create properly salted and hashed passwords.
  • WebImage. Renders an image.
  • WebMail. Sends an email message.

Controller Improvements

Global Action Filters

Sometimes you want to perform logic either before an action method runs or after an action method runs. To support this, ASP.NET MVC 2 provided action filters. Action filters are custom attributes that provide a declarative means to add pre-action and post-action behavior to specific controller action methods. However, in some cases you might want to specify pre-action or post-action behavior that applies to all action methods. MVC 3 lets you specify global filters by adding them to theGlobalFilters collection. For more information about global action filters, see the following resources:

New "ViewBag" Property

MVC 2 controllers support a ViewData property that enables you to pass data to a view template using a late-bound dictionary API. In MVC 3, you can also use somewhat simpler syntax with the ViewBagproperty to accomplish the same purpose. For example, instead of writingViewData["Message"]="text", you can write ViewBag.Message="text". You do not need to define any strongly-typed classes to use the ViewBag property. Because it is a dynamic property, you can instead just get or set properties and it will resolve them dynamically at run time. Internally, ViewBagproperties are stored as name/value pairs in the ViewData dictionary. (Note: in most pre-release versions of MVC 3, the ViewBag property was named the ViewModel property.)

New "ActionResult" Types

The following ActionResult types and corresponding helper methods are new or enhanced in MVC 3:
  • HttpNotFoundResult. Returns a 404 HTTP status code to the client.
  • RedirectResult. Returns a temporary redirect (HTTP 302 status code) or a permanent redirect (HTTP 301 status code), depending on a Boolean parameter. In conjunction with this change, theController class now has three methods for performing permanent redirects: RedirectPermanent,RedirectToRoutePermanent, and RedirectToActionPermanent. These methods return an instance of RedirectResult with the Permanent property set to true.
  • HttpStatusCodeResult. Returns a user-specified HTTP status code.

JavaScript and Ajax Improvements

By default, Ajax and validation helpers in MVC 3 use an unobtrusive JavaScript approach. Unobtrusive JavaScript avoids injecting inline JavaScript into HTML. This makes your HTML smaller and less cluttered, and makes it easier to swap out or customize JavaScript libraries. Validation helpers in MVC 3 also use the jQueryValidate plugin by default. If you want MVC 2 behavior, you can disable unobtrusive JavaScript using a web.config file setting. For more information about JavaScript and Ajax improvements, see the following resources:

Client-Side Validation Enabled by Default

In earlier versions of MVC, you need to explicitly call the Html.EnableClientValidation method from a view in order to enable client-side validation. In MVC 3 this is no longer required because client-side validation is enabled by default. (You can disable this using a setting in the web.config file.)
In order for client-side validation to work, you still need to reference the appropriate jQuery and jQuery Validation libraries in your site. You can host those libraries on your own server or reference them from a content delivery network (CDN) like the CDNs from Microsoft or Google.

Remote Validator

ASP.NET MVC 3 supports the new RemoteAttribute class that enables you to take advantage of the jQuery Validation plug-in's remote validator support. This enables the client-side validation library to automatically call a custom method that you define on the server in order to perform validation logic that can only be done server-side.
In the following example, the Remote attribute specifies that client validation will call an action namedUserNameAvailable on the UsersController class in order to validate the UserName field.
public class User {
    [Remote("UserNameAvailable", "Users")]
    public string UserName { get; set; }
}
The following example shows the corresponding controller.
public class UsersController { 
    public bool UserNameAvailable(string username) 
    { 
        if(MyRepository.UserNameExists(username)) 
        { 
            return "false"; 
        } 
        return "true"; 
    } }
For more information about how to use the Remote attribute, see How to: Implement Remote Validation in ASP.NET MVC in the MSDN library.

JSON Binding Support

ASP.NET MVC 3 includes built-in JSON binding support that enables action methods to receive JSON-encoded data and model-bind it to action-method parameters. This capability is useful in scenarios involving client templates and data binding. (Client templates enable you to format and display a single data item or set of data items by using templates that execute on the client.) MVC 3 enables you to easily connect client templates with action methods on the server that send and receive JSON data. For more information about JSON binding support, see the JavaScript and AJAX Improvements section of Scott Guthrie's MVC 3 Preview blog post.

Model Validation Improvements

"DataAnnotations" Metadata Attributes

ASP.NET MVC 3 supports DataAnnotations metadata attributes such as DisplayAttribute.

"ValidationAttribute" Class

The ValidationAttribute class was improved in the .NET Framework 4 to support a new IsValidoverload that provides more information about the current validation context, such as what object is being validated. This enables richer scenarios where you can validate the current value based on another property of the model. For example, the new CompareAttribute attribute lets you compare the values of two properties of a model. In the following example, the ComparePassword property must match the Password field in order to be valid.
public class User
{ 
    [Required]
    public string Password { get; set; } 
    [Required, Compare("Password")] 
    public string ComparePassword { get; set; } }

Validation Interfaces

The IValidatableObject interface enables you to perform model-level validation, and it enables you to provide validation error messages that are specific to the state of the overall model, or between two properties within the model. MVC 3 now retrieves errors from the IValidatableObject interface when model binding, and automatically flags or highlights affected fields within a view using the built-in HTML form helpers.
The IClientValidatable interface enables ASP.NET MVC to discover at run time whether a validator has support for client validation. This interface has been designed so that it can be integrated with a variety of validation frameworks.
For more information about validation interfaces, see the Model Validation Improvements section ofScott Guthrie's MVC 3 Preview blog post. (However, note that the reference to "IValidateObject" in the blog should be "IValidatableObject".)

Dependency Injection Improvements

ASP.NET MVC 3 provides better support for applying Dependency Injection (DI) and for integrating with Dependency Injection or Inversion of Control (IOC) containers. Support for DI has been added in the following areas:
  • Controllers (registering and injecting controller factories, injecting controllers).
  • Views (registering and injecting view engines, injecting dependencies into view pages).
  • Action filters (locating and injecting filters).
  • Model binders (registering and injecting).
  • Model validation providers (registering and injecting).
  • Model metadata providers (registering and injecting).
  • Value providers (registering and injecting).
MVC 3 supports the Common Service Locator library and any DI container that supports that library'sIServiceLocator interface. It also supports a new IDependencyResolver interface that makes it easier to integrate DI frameworks.





No comments:

Post a Comment