• Home
  • About
  • Contact
  • ado.net
  • angular
  • c#.net
  • design patterns
  • linq
  • mvc
  • .net core
    • .Net Core MVC
    • Blazor Tutorials
  • sql
  • web api
  • dotnet
    • SOLID Principles
    • Entity Framework
    • C#.NET Programs and Algorithms
  • Others
    • C# Interview Questions
    • SQL Server Questions
    • ASP.NET Questions
    • MVC Questions
    • Web API Questions
    • .Net Core Questions
    • Data Structures and Algorithms

ASP.NET MVC Data Annotations Interview Questions

In this article, I am going to discuss the Most Frequently asked ASP.NET MVC Data Annotations Interview Questions with Answers. Please read our previous article where we discussed the most frequently asked Action Methods Interview Questions in ASP.NET MVC Application with Answers.

What are 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.

Built-in Data Annotation Validator Attributes in ASP.NET MVC
  • DataType – Specify the datatype of a property
  • DisplayName – specify the display name for a property.
  • DisplayFormat – specify the display format for a property like the different format for a Date property.
  • Required – Specify a property as required.
  • Regular Expression – validate the value of a property by the specified regular expression pattern.
  • Range – validate the value of a property within a specified range of values.
  • StringLength – specify min and max length for a string property.
  • MaxLength – specify max length for a string property.
  • Bind – specify fields to include or exclude when adding parameter or form values to model properties.
  • 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 the server-side:

Explicit Model Validation in ASP.NET MVC
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 in ASP.NET MVC
The Data Annotations were 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.
ASP.NET MVC Data Annotations Interview Questions and Answers

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 within 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 what are the advantages of using 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 of using CDN:
  • It reduces the load from your application server.
  • It saves bandwidth since jQuery and other open libraries/framework will load faster from these CDN.
  • 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 the 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 requests to the server and size of requested CSS and JavaScript, which improve page loading time.

A bundle is a logical group of files that are loaded with a single HTTP request. You can create style and script bundle for CSS and Java Scripts respectively by calling the BundleCollection class Add() method. All bundles are created within 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"));
    }
}

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 causes 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.NET MVC4?
The System.Web.Optimization class offers the bundling and minification techniques that exist within Microsoft.Web.Optimization dll. Using this dll you can also use this technique with ASP.NET MVC3 and .NET Framework 4.0.

How Bundling uses 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.

In the next article, I am going to discuss the most frequently asked ASP.NET MVC Filters Interview Questions with Answers. Here, in this article, I try to explain the most frequently asked ASP.NET MVC Data Annotations Interview Questions with Answers. I hope this article will help you with your needs. I would like to have your feedback. Please post your feedback, question, or comments about this article.

0 comments:

Post a Comment

If you like this website, please share with your friends on Facebook, Twitter, LinkedIn.

Join us on Telegram

Loved Our Blog Posts? Subscribe To Get Updates Directly To Your Inbox

Like us on Facebook

Popular Posts

  • Comparison Between HttpModule and HttpContext
    Hi friends! Today we are going to list some of the differences between HttpModule and HttpContext. Many of my developer friends are confus...
  • Recursion And Back Tracking
    In this article, I am going to discuss Recursion And BackTracking in detail. Please read our previous article where we discussed Master Th...
  • How to Reverse a String in C#
    In this article, I am going to discuss How to Reverse a String in C# with and without using built-in Methods. Please read our previous art...
  • Reverse Number Program in C# with Examples
    In this article, I am going to discuss the Reverse Number Program in C# with some examples. Please read our previous article where we discu...
  • Armstrong Number Program in C# with Examples
    In this article, I am going to discuss the Armstrong Number Program in C# with some examples. Please read our previous article before proc...
  • Binary to Decimal Conversion in C# with Examples
    In this article, I am going to discuss the Binary to Decimal Conversion in C# with some examples. Please read our previous article where w...
  • Decimal to Binary Conversion in C# with Examples
    In this article, I am going to discuss the Decimal to Binary Conversion in C# with some examples. Please read our previous article where w...

Blog Archive

Contact Form

Name

Email *

Message *

Tags

.Net .Net Core .Net Core MVC Algorithm Angular Anonymous Types Asp.Net Asp.Net MVC Blazor C# Data Structure Database Design Patterns Entity Framework Entity Framework Core Filters Interview Question Management Studio Programming Programs SQL Server SSMS Web API

Copyright © C# Techtics | All Right Reserved.

Protected by Copyscape