Tuesday, 9 July 2013

C# Tips : Required Field Validation using Annotations in ASP.Net MVC framework

Click Here to Download MVCValidationUsingAnnotations.zip Example.
 
Data annotations are uses for validation purposes. We can use annotations attribute on a model property. You can find data annotations in System.ComponentModel.DataAnnotations namespace. But there are attributes also available outside this namespace.

These attributes provide server-side validation and client-side validation. Here we are demonstrating "Required" attribute. This is a basic validation in each and every project or application we need required field validation.

Here is example for this.



In this example we take "customer" example. We take one "Customer" model in this, we have three fields like FirstName, LastName and Email. Now we need required validation on "FirstName" and "LastName" field. So we simply put "[Required]" attribute on "FirstName" and "LastName" property in "Customer" model.

[Required]
public string FirstName { get; set; }

[Required]
public string LastName { get; set; }

The attribute generate a validation error if either property value is null or empty.

At the view side we have to add this code :

     @Html.ValidationMessageFor(model => model.FirstName,"", new { style="color:red"})
     @Html.ValidationMessageFor(model => model.LastName,"", new { style="color:red"})

This is used to display error messages at client side. By default it will generate its own error message, but you can also customize it. Here in "ValidationMessageFor" method we add HTMLAttribute for style.

Here is Code for this. 

Model (Customer.cs): 

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;

namespace MVCValidationUsingAnnotations.Models
{
    public class Customer
    {
        public int CustomerID { get; set; }

        [Required]
        public string FirstName { get; set; }

        [Required]
        public string LastName { get; set; }

        public string Email { get; set; }

    }
}

Controller (CustomerController.cs) : 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace MVCValidationUsingAnnotations.Controllers
{
    public class CustomerController : Controller
    {
        //
        // GET: /Customer/

        public ActionResult Index()
        {
            return View();
        }

        //
        // GET: /Customer/Details/5

        public ActionResult Details(int id)
        {
            return View();
        }

        //
        // GET: /Customer/Create

        public ActionResult Create()
        {
            return View();
        }

        //
        // POST: /Customer/Create

        [HttpPost]
        public ActionResult Create(FormCollection collection)
        {
            try
            {
                if (ModelState.IsValid)
                {

                    return RedirectToAction("Create");
                }
                else
                {
                    return View();
                }
            }
            catch
            {
                return View();
            }
        }

      
    }
}

View (Create.chtml):

@model MVCValidationUsingAnnotations.Models.Customer

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Create</title>
</head>
<body>
    <script src="~/Scripts/jquery-1.7.1.min.js"></script>
    <script src="~/Scripts/jquery.validate.min.js"></script>
    <script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
    
    @using (Html.BeginForm()) {
        @Html.ValidationSummary(true)
    
        <fieldset>
            <legend>Customer</legend>
    
            <div class="editor-label">
                @Html.LabelFor(model => model.FirstName)
            </div>
            <div class="editor-field">
                @Html.EditorFor(model => model.FirstName)
                @Html.ValidationMessageFor(model => model.FirstName,"", new { style="color:red"})
            </div>
    
            <div class="editor-label">
                @Html.LabelFor(model => model.LastName)
            </div>
            <div class="editor-field">
                @Html.EditorFor(model => model.LastName)
                @Html.ValidationMessageFor(model => model.LastName,"", new { style="color:red"})
            </div>
    
            <div class="editor-label">
                @Html.LabelFor(model => model.Email)
            </div>
            <div class="editor-field">
                @Html.EditorFor(model => model.Email)
                @Html.ValidationMessageFor(model => model.Email)
            </div>
    
            <p>
                <input type="submit" value="Create" />
            </p>
        </fieldset>
    }
   
</body>
</html>

Output :
Required Field Validation using Annotations in ASP.Net MVC framework
(To view original image , click on image)


Below are the books that you would like :

No comments:

Post a Comment

Post a Comment