MVC Data Annotations Interview Questions

ASP.NET MVC Data Annotations Interview Questions

In this article, I will discuss Most Frequently asked MVC Data Annotations Interview Questions and Answers.

What are the Data Annotations in ASP.NET MVC?         

Data validation is a key aspect of developing a web application. In Asp.net MVC, we can easily apply validation to the web application by using Data Annotation attribute classes to the model class. Data Annotation attribute classes are present in System.ComponentModel.DataAnnotations namespace and are available to Asp.net projects like Asp.net web application & website, Asp.net MVC, Web forms and also to Entity framework ORM models. 

Data Annotations help us to define the rules to the model classes or properties for data validation and displaying suitable messages to end users.

Data Annotation Validator Attributes          
  1. DataType – Specify the datatype of a property      
  2. DisplayName – specify the display name for a property.     
  3. DisplayFormat – specify the display format for a property like the different format for Date property.        
  4. Required – Specify a property as required.             
  5. regular expression – validate the value of a property by specified regular expression pattern. 
  6. Range – validate the value of a property within a specified range of values.  
  7. StringLength – specify min and max length for a string property.
  8. MaxLength – specify max length for a string property.
  9. Bind – specify fields to include or exclude when adding parameter or form values to model properties.
  10. ScaffoldColumn – specify fields for hiding from editor forms.
How to apply Server-side validation in ASP.NET MVC?

The Server-side validations are very important before playing with sensitive information of a user. Server-side validation must be done whether we validate the received data on the client side. A user could disable script in his browser or do something else to bypass client-side validation. In this case, server-side validation must require to protect our data from the dirty input.

In ASP.NET MVC, there are two ways to validate a model on server side:

Explicit Model Validation

This is the traditional way to validate the model data by using IF..Else..IF statement. In this way, you need to check your model property values one by one for your desired result. If model property values are unexpected, inject error messages within ModelState.

public class HomeController : Controller
{
    [HttpPost]
    public ActionResult ExplicitServer(UserViewModel model)
    {
        //Write custom logic to validate UserViewModel
        if (string.IsNullOrEmpty(model.UserName))
        {
            ModelState.AddModelError("UserName", "Please enter your name");
        }

        if (!string.IsNullOrEmpty(model.UserName))
        {
            Regex emailRegex = new Regex(".+@.+\..+");
            if (!emailRegex.IsMatch(model.UserName))
                ModelState.AddModelError("UserName", "Please enter correct email address");
        }
        if (ModelState.IsValid) //Check model state
        {
            //TO DO:
        }
    }
}
Model Validation with Data Annotations 

The Data Annotations was introduced with .NET 3.5 SP1. It has a set of attributes and classes defined in the System.ComponentModel.DataAnnotations assembly. Data Annotations allow us to decorate model classes with metadata. This metadata describes a set of rules that are used to validate a property.

public class UserViewModel
{
    [Required(ErrorMessage = "Please Enter Email Address")]
    [RegularExpression(".+@.+\..+", ErrorMessage = "Please Enter Correct Email Address")]
    public string UserName { get; set; }

    [Required(ErrorMessage = "Please Enter Password")]
    [StringLength(50, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
    public string Password { get; set; }
}
How to determine there is no error in Model State?

When server side model validation fails, errors are included in the ModelState. Hence, by using ModelState.IsValid property you can verify model state. It returns true if there is no error in ModelState else returns false.

[HttpPost]
public ActionResult DoSomething(UserViewModel model)
{
    if (ModelState.IsValid)
    {
        //TODO:
    }
    return View();
}
How to enable and disable client-side validation in ASP.NET MVC?

We can enable and disable the client-side validation by setting the values of ClientValidationEnabled & UnobtrusiveJavaScriptEnabled keys true or false. This setting will be applied to application level.

<add key=”ClientValidationEnabled” value=”true” /> <add key=”UnobtrusiveJavaScriptEnabled” value=”true” />

For client-side validation, the values of above both the keys must be true. When we create new project using Visual Studio in MVC3 or MVC4, by default the values of both the keys are set to true.

We can also enable the client-side validation programmatically. For this we need to do code with in the Application_Start() event of the Global.asax, as shown below.

protected void Application_Start()
{
    //Enable or Disable Client Side Validation at Application Level 
    HtmlHelper.ClientValidationEnabled = true;
    HtmlHelper.UnobtrusiveJavaScriptEnabled = true;
}

We can also enable or disable client-side validation for a specific view. For this, we required to enable or disable client-side validation inside a Razor code block as shown below. This option will override the application level settings for that specific view.

@using MvcApp.Models @{
    ViewBag.Title = "About";
    HtmlHelper.ClientValidationEnabled = false;
}
What is a CDN and advantages of CDN?

CDN stands for content delivery network or content distribution network (CDN) which is a large distributed system of servers deployed in multiple data centers across the Internet. The goal of a CDN is to serve the content (like the jQuery library and other open source libraries) to end-users with high availability and high performance.

There are three popular CDN – Google, Microsoft and jQuery.

Google CDN

<script type=”text/javascript” src=”http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js”></script>

Microsoft CDN

<script type=”text/javascript” src=”http://ajax.microsoft.com/ajax/jquery/jquery-1.9.1.min.js”></script>

JQuery CDN

<script type=”text/javascript” src=”http://code.jquery.com/jquery-1.9.1.min.js”></script>

Advantages
  1. It reduces the load from your application server.
  2. It saves bandwidth since jQuery and other open libraries/framework will load faster from these CDN.
  3. The most important benefit is it will be cached means if a user has visited any site which is using jQuery framework from any of these CDN and your web application is also using the same CDN for serving the jQuery then for your application, it will not request the jQuery from CDN.
What is jquery.validate.unobtrusive.js?
Or what is jQuery Validation Unobtrusive plugin?

Microsoft introduced jquery.validate.unobtrusive.js plugin with ASP.NET MVC3 to apply data model validations to the client side using a combination of jQuery Validation and HTML 5 data attributes.

What is Bundling and Minification in ASP.NET MVC?

ASP.NET MVC4 and .NET Framework 4.5 offer bundling and minification techniques that reduce the number of request to the server and size of requested CSS and JavaScript, which improve page loading time.

A bundle is a logical group of files that is loaded with a single HTTP request. You can create style and script bundle for CSS and Java Scripts respectively by calling BundleCollection class Add() method. All bundles are create with in BundleConfig.cs file.

public class BundleConfig
{
    public static void RegisterBundles(BundleCollection bundles)
    {
        bundles.Add(new StyleBundle("~/Content/css").Include("~/Content/site.min.css",
                       "~/Content/mystyle.min.css"));

        bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include("~/Scripts/jquery-1.7.1.min.js",
                        "~/Scripts/jquery.validate.min.js",
                        "~/Scripts/jquery.validate.unobtrusive.min.js"));
    }
}

The Minification is a technique for removing unnecessary characters (like white space, newline, tab) and comments from the JavaScript and CSS files to reduce the size which cause improved load times of a webpage. There are so many tools for minifying the js and CSS files. JSMin and YUI Compressor are the two most popular tools for minifying js and CSS files.

Can we use Bundling and Minification in ASP.NET MVC3 or ASP.NET4.0?

System.Web.Optimization class offers the bundling and minification techniques that exist within the Microsoft.Web.Optimization dll. Using this dll you can also use this technique with ASP.NET MVC3 and .NET Framework 4.0.

How Bundling use browser Cache capability?

Browsers cache resources based on URLs. When a web page requests a resource, the browser first checks its cache to see if there is a resource with the matched URL. If yes, then it simply uses the cached copy instead of fetching a new one from the server. Hence whenever you change the content of CSS and JS files will not reflect on the browser. For this, you need to force the browser for refreshing/reloading.

But bundles automatically take care of this problem by adding a hash code to each bundle as a query parameter to the URL as shown below. Whenever you change the content of CSS and a JS file then a new hash code will be generated and rendered to the page automatically. In this way, the browser will see a different Url and will fetch the new copy of CSS and JS.

SUMMARY

In this article, I try to explain most frequently asked MVC Data Annotations Interview Questions and Answers. I hope this article will help you with your need. I would like to have your feedback. Please post your feedback, question, or comments about this article.

Leave a Reply

Your email address will not be published. Required fields are marked *