Table of contents
1.
Introduction
2.
ASP.NET MVC Input Validation
2.1.
The Base Validator Class
2.2.
Commonly Used Validation Annotations
2.3.
DRY Principle
3.
Understanding MVC Validation with an Example
3.1.
Controller
3.2.
Model
3.3.
View
3.4.
Output
3.5.
Functions of a Controller
3.6.
Working of a Controller
4.
Creating a Controller
5.
Adding a View Page
6.
Frequently Asked Questions
7.
Key Takeaways
Last Updated: Jun 25, 2025

ASP.NET MVC Validations

Author Naman Kukreja
1 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

On the internet, whenever you sign in on any website or fill in the details, you see some remarks like "the password entered is incorrect", " this field is required".

So what are all these statements?

These statements come from validations that the programmer has set so that any unidentified user cannot access the content. While moving further in the blog, we will learn more about this.

So without wasting any time further, let's dive into our topic.

ASP.NET MVC Input Validation

Validation is the process of checking and verifying the user's details and redirecting him accordingly. This is an essential task for the programmer. 

The application must allow only valid users to access the content, checking their entered information.

ASP.NET provides some inbuilt annotations that users can apply to model properties.

The Base Validator Class

There are many validators in ASP.NET, and all of them inherit the methods and properties of the base class validators. Here are the methods and the properties of the base validator class:

  1. ControlToValidate: It indicates the input control to validate. This is a mandatory attribute. It must be unique.
  2. Text: It holds the message to be displayed in case of failure.
  3. Enabled: It disables or enables the validator.
  4. IsValid: The boolean attribute indicates whether the control is valid or not.
  5. Validate(): This method updates the IsValid and revalidates the control.

Commonly Used Validation Annotations

These are some commonly used annotations with their explanation:

DRY Principle

One of the core design principles of ASP.NET MVC is DRY, which stands for Don’t Repeat Yourself. It is mainly used from the development perspective as in this, we specify the functionality at one place and then use it in the whole application.

This has an advantage as it reduces the amount of code and makes the code easy to maintain.

Understanding MVC Validation with an Example

In this example, we will use annotations. The order that we follow in this example is: First, we will create the controller, then the model, and after that, the view followed by output.

Controller

This is the syntax for creating a controller. Here we are creating a student controller:

using System;  
using System.Collections.Generic;  
using System.Linq;  
using System.Web;  
using System.Web.Mvc;  
namespace MvcApplicationDemo.Controllers  
{  
    public class StudentsController : Controller  
    {  
        // GET: Students  
        public ActionResult Index()  
        {  
            return View();  
        }  
    }  
} 

Model

Here we are creating a student model:

using System.ComponentModel.DataAnnotations;  
  
namespace MvcApplicationDemo.Models  
{  
    public class Student  
    {  
        public int ID { get; set; }  
        // -- Validating Student Name  
        [Required(ErrorMessage ="Name is required")]  
        [MaxLength(12)]  
        public string Name { get; set; }  
        // -- Validating Contact Number  
        [Required(ErrorMessage = "Contact is required")]  
        [DataType(DataType.PhoneNumber)]  
        [RegularExpression(@"^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$", ErrorMessage = "Not a valid Phone number")]  
        public string Contact { get; set; }
        // -- Validating Email Address  
        [Required(ErrorMessage ="Email is required")]  
        [EmailAddress(ErrorMessage = "Invalid Email Address")]  
        public string Email { get; set; }  
       
    }  
}

View

Now this will be the view that is visible to the user on the front end:

@model MvcApplicationDemo.Models.Student  
@{  
    ViewBag.Title = "Index";  
}  
<h2>Index</h2>  
@using (Html.BeginForm())  
{  
    @Html.AntiForgeryToken()  
    <div class="form-horizontal">  
        <h4>Student</h4>  
        <hr />  
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })  
        <div class="form-group">  
            @Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" })  
            <div class="col-md-10">  
                @Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })  
                @Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" })  
            </div>  
        </div>  
   <div class="form-group">  
            @Html.LabelFor(model => model.Contact, htmlAttributes: new { @class = "control-label col-md-2" })  
            <div class="col-md-10">  
                @Html.EditorFor(model => model.Contact, new { htmlAttributes = new { @class = "form-control" } })  
                @Html.ValidationMessageFor(model => model.Contact, "", new { @class = "text-danger" })  
            </div>  
        </div> 
        <div class="form-group">  
            @Html.LabelFor(model => model.Email, htmlAttributes: new { @class = "control-label col-md-2" })  
            <div class="col-md-10">  
                @Html.EditorFor(model => model.Email, new { htmlAttributes = new { @class = "form-control" } })  
                @Html.ValidationMessageFor(model => model.Email, "", new { @class = "text-danger" })  
            </div>  
        </div>  
      
        <div class="form-group">  
            <div class="col-md-offset-2 col-md-10">  
                <input type="submit" value="Create" class="btn btn-default" />  
            </div>  
        </div>  
    </div>  
}  
<div>  
    @Html.ActionLink("Back to List", "Index")  
</div>  
@section Scripts {  
    @Scripts.Render("~/bundles/jqueryval")  
} 

Output

We can see in the below attached screenshot that it validates the empty fields and displays the message that these fields are required.

In the below-attached screenshot, we are validating the entered data.

 

 

Functions of a Controller

A controller is mainly responsible for performing the following tasks:

  1. It locates the appropriate action method to call and validate the requests.
  2. It gets the values to use as the action method's arguments.
  3. It handles all the errors that might occur during the execution of the action.
  4. It uses the WebFormViewEngine class for rendering the ASP.Net page.

 

Working of a Controller

 

Source: Link

  1. The user requests through the ASP.Net website.
  2. All these requests then reach the controllers. 
  3. The controller asks the models for data. 
  4. These models further perform database operations and respond to the controller with the required data.
  5. The controller retrieves the data from the model.
  6. Then, the controller renders an HTML page with model data and creates a view page.
  7. Further, the controller responds to the user with the View Page. 

Creating a Controller

This section will understand how the controller and view page work together.

  • Go to the menubar, click on the file and create a new project.

 

 

  • Choose ASP.NET Web Application (.NET Framework) as your project template.
     

 

  • Configure your project, assign it with a name and create the project.
     

 

  • Make sure that you press the right choices, i.e., An empty template, no authentication, and checkmark the MVC under the add folders & core references heading. Refer to the image given below.
     

 

  • Go to visual studio, right-click on the controller folder -> Add -> controller.
     

This will open an “Add scaffold” dialog box.
(Scaffolding is an automatic code generation framework for ASP.Net web applications. Scaffolding reduces the time to develop a controller, view, etc., in the MVC framework.)

 

  • Select MVC 5 Controller- empty and click on the add button.

 

 

  • Then, give the controller name to the ItemController. “Controller” suffix must be added in the controller name. Every controller must be located in the controller folder. Here, we are assigning the name Ninja to our controller. Further, click on the add button to add the controller.
     

 

  • This will create the NinjaController class with the Index() method in NinjaController.cs file under the controller folder.
     

 

  • The NinjaController class is derived from the Controller class. A controller in MVC must be derived from the abstract controller class. This base controller class also contains helper methods that can be used for multiple purposes.
     
  • Now, we can return a dummy string from the index action method of the controller that we have defined. Change the return type of the index method from ActionResult to string and return any dummy string of your choice. Refer to the image given below. 

 


(If you face any issues while debugging, try changing the default controller name from “Home” to “your file name” in the RouteConfig.cs file under App_Start folder.)
 

Output:

 

Adding a View Page

A view in the ASP.Net MVC is responsible for the user interface. The view displays the data coming from the models. It is an HTML template that binds and displays HTML controls with data. The “.cshtml” file uses the Razor view engine, and .cshtml views are used in C# programming. It is a combination of C# and HTML (.cshtml). The return type can either be “ViewResult” or “ActionResult.”

A view can contain the following extension depending on the language:

  1. .aspx
  2. .asp
  3. .html
  4. .cshtml
  5. .vbhtml

 

Let’s create a view page to understand the concept better. Refer to the following steps:

  • Right-click on the index action method and select add view option from the dialog box.
     


 

  • A dialog box named add view will appear on the screen, as shown below. Click on the MVC5 view and press the add button to add the view page.
     

 

 

  • An index view page will be added named “filename.cshtml”. In this case, it is Index.cshtml.
     

 

The view file initially will look something like this:
 

 

  • Add the following code to the NinjaController.cs file.
     

 

  • Add the following code in Index.cshtml file.
<h1>@ViewBag.NinjaList</h1>

 

  • Now, run the project (or press Ctrl + F5). You will see a window popping up which will contain your desired output.
     

Output:

 

If you pay attention to the URL given below: 
 

Note that the controller will execute on the above link. Here, Ninja represents the controller, and Index represents the action method. The incoming URL in an ASP.Net MVC application is mapped to the controller action method.  

Frequently Asked Questions

1. Write some features of ASP.NET.

Answer: It can separate server-side code with the HTML layout and uses C# and VB.NET as languages to make the website.

2. What is a round trip?

Answer: It is the trip of a web page from client to server and then again from server to client.

3. Name some page events in ASP.NET.

Answer: Some page events in ASP.NET are preinit, init, PreLoad, Load, Render, PreRender, etc.

4. How many types of validations are there in ASP.NET?

Answer: There are mainly two validations in ASP.NET: client-side and server-side.

Key Takeaways

In this blog, we have learned about MVC validations by explaining the base class validator, the standard annotations used during validation, and examples with Model, View, Controller.

 If you want to learn about Webform LinkButton in ASP.Net, look at this blog. Here, you will get the idea of what they are and the Features Of ASP Net with examples.

Recommended Readings:

 

Live masterclass