Introduction:

In this section we will learn how to implement data validations in the ASP.NET MVC or How to use data validations in the ASP.NET MVC application with example.


Description:

DataAnnotations:

In ASP.NET MVC use DataAnnotations attributes to implement validations. DataAnnotations includes validation attributes for different validation rules, which can be applied to the properties of model class. ASP.NET MVC framework will automatically enforce these validation rules and display validation messages in the view.

The DataAnnotations attributes included in System.ComponentModel.DataAnnotations namespace. The following lists DataAnnotations validation attributes.


v  Range – Enable to you Defines a maximum and minimum value for a numeric field.

v  RegularExpression – Enable to you Specify the field value must match with specified Regular                            Expression.

v  Required – Enable to you make property is a required field.  

v  StringLength – Enable to you Define  a maximum length for string field.

v  Validation – Validation is the base class for all validator attributes.


Let's start to implement validation in User Form.

Step 1: First of all, apply DataAnnotation attribute on the properties of user model class. We want to validate that UserName and ContactNumber is not blank.  

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
 
namespace MVC_Tutorials.Models
{
    public class User
    {
        public int UserId { get; set; }
 
        [Required, Display(Name = "User Name")]
        public string UserName { get; set; }
 
        [Required, Display(Name = "Contact Number")]
        public int ContactNumber { get; set; }
 
    }
}

In the above example, we have applied a Required attribute to the UserName property And ContactNumber property. So now, the MVC framework will automatically display the default error message, if the user tries to save the user form without entering the User Name and Contact Number.


Step 2: Create the GET and POST User Action method. The GET action method will render User view and the POST User method will save user data as shown below.

using MVC_Tutorials.Models;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace MVC_Tutorials.Controllers
{
    public class HomeController : Controller
    {
 
        public ActionResult User()
        {
            return View();
        }
        [HttpPost]
        public ActionResult User(User obj)
        {
            if (ModelState.IsValid)
            {               
 
                return RedirectToAction("Index");
            }
 
            return View(obj);
        }
        
    }     }


        Step 3: Now, create a User view for User

@model
MVC_Tutorials.Models.User
@{
    Layout = null;
}
<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>User</title>
    <link href="/Content/bootstrap.css" rel="stylesheet" />
    <script src="/Scripts/jquery-3.1.1.js"></script>
    <script src="/Scripts/bootstrap.min.js"></script>
 
</head>
<body>
    <div class="container">
        @using (Html.BeginForm())
        {
            @Html.AntiForgeryToken()
            <div class="form-horizontal">
                <h4>User Form</h4>
                <hr />
                @Html.ValidationSummary(true, "", new { @class = "text-danger" })
                @Html.HiddenFor(model => model.UserId)
 
                <div class="form-group">
                  @Html.LabelFor(model => model.UserName, htmlAttributes: new { @class = "control-labelcol-md-2" })
                    <div class="col-md-10">
      @Html.EditorFor(model => model.UserName, new { htmlAttributes = new { @class = "form-control" } })
     @Html.ValidationMessageFor(model=> model.UserName, "", new { @class = "text-danger" })
                    </div>
                </div>
 
                <div class="form-group">
                @Html.LabelFor(model =>                model.ContactNumber, htmlAttributes: new { @class = "control-label col-md-2" })
                    <div class="col-md-10">
                 @Html.EditorFor(model =>                 model.ContactNumber, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model=>        
                model.ContactNumber, "", new { @class = "text-danger" })
                    </div>
                </div>
 
                <div class="form-group">
                    <div class="col-md-offset-2 col-md-10">
                        <input type="submit" value="Save" class="btn btn-default" />
                    </div>
                </div>
            </div>
        }
    </div>
</body>
</html>

As you can see in the above User.cshtml, it calls Html Helper method ValidationMessageFor for every field and ValidationSummary method at the top. ValidationMessageFor is responsible to display error message for the specified field. ValidationSummary displays a list of all the error messages at once.

 

So now, it will display default validation message when you submit a user form without entering a UserName or ContactNumber.


How to Implement Data Validation in MVC


I hope it will help to you.

0 comments


Leave a comment

Make sure you enter the (*) required information where indicated. HTML code is not allowed.

You may also like