Click here to Skip to main content
13,193,551 members (47,424 online)
Click here to Skip to main content
Add your own
alternative version

Stats

49.5K views
9 bookmarked
Posted 17 Oct 2013

Implementing Remote Validation in MVC

, 17 Oct 2013
Rate this:
Please Sign up or sign in to vote.
Validating MVC fields at by ajax call on controller without posting form data.

Introduction

Remote validation is used to make server calls to validate data without posting the entire form to the server when server side validation is preferable to client side.  It's all done set up model and controller which is pretty neat.   

Suppose if any field in database table that must be unique and we want to check this uniqueness on client side(after text change of text-boxes) instead of posting whole page.

Now consider a simple example in which we have saved the catalog information into database table say "Catalog". Catalog table has columns below:

Id as PK, CatalogName, Barcode(must be unique)

Using Validation Code

Step 1: Create model for Catalog table and apply the the remote validation for the column that must be validated on client side.

Step 2: Write a method in controller to check the validation for that column. You can also send the additional parameters by adding AdditionFields attribute.

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

namespace ItemCatalog.Models
{
    public class Catalog
    {
        [Required]
        public long Id { get; set; }

        [Required]
        [Display(Name = "Item Name")]
        public string CatalogName { get; set; }

        [Required]
        [Display(Name = "Bar code")]
        [Remote("IsBarCodeUnique","Catalog",AdditionalFields="CatalogName",ErrorMessage="This {0} is already used.")]
        public string Barcode { get; set; }
    }
} 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using ItemCatalog.Models;

namespace ItemCatalog.Controllers
{
    public class CatalogController : Controller
    {
        //
        // GET: /Catalog/

        public ActionResult Catalog()
        {
            Catalog catalog = new Catalog();
            return View(catalog);
        }

        public JsonResult SaveCatalog(Catalog catalog)
        {
            // Action to save the data
            return Json(true);
        }

        public JsonResult IsBarCodeUnique(Catalog catalog)
        {
            return IsExist(catalog.CatalogName, catalog.Barcode)
                ? Json(true, JsonRequestBehavior.AllowGet)
                : Json(false, JsonRequestBehavior.AllowGet);
        }

        public bool IsExist(string catalogName, string barcode)
        {
            //True:False--- action that implement to check barcode uniqueness

            return false;//Always return false to display error message
        }
    }
}
@model ItemCatalog.Models.Catalog
@{
    ViewBag.Title = "Catalog";
    Layout = "~/Views/Shared/_Layout.cshtml";
}
@section scripts {
    <style type="text/css">
        .row
        {
            float: left;
            width: 100%;
            padding: 10px;
        }
        .row label
        {
            width: 100px;
            float: left;
        }
        
        #success-message
        {
            color: Green;
        }
    </style>
    <script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
    <script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
    <script type="text/javascript">

        function SaveCatalogComplete(result) {
            $("#success-message").show();
        }

    </script>
}
<h2>
    Item</h2>
@using (Ajax.BeginForm("SaveCatalog", new AjaxOptions { HttpMethod = "POST", OnSuccess = "SaveCatalogComplete" }))
{ 
    
    <fieldset>
        <div class="row">
            @Html.LabelFor(x => x.CatalogName)
            @Html.TextBoxFor(x => x.CatalogName, Model.CatalogName)
            @Html.ValidationMessageFor(x => x.CatalogName)
        </div>
        <div class="row">
            @Html.LabelFor(x => x.Barcode)
            @Html.TextBoxFor(x => x.Barcode, Model.Barcode)
            @Html.ValidationMessageFor(x => x.Barcode)
        </div>
    </fieldset>
   
    <div id="success-message" style="display: none;">
        This record is successfully saved!!
    </div>
    <div>
        <input type="submit" value="Save" />
    </div>
}

Step 3: Return the JsonResult object as per validation response.  

Summary :  

It's easy to implement and gives the same type of error message results without writing any Ajax to call server side validation.  

 

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Sachin Dev Tripathi
Software Developer Daffodil software limited
India India
No Biography provided

You may also be interested in...

Comments and Discussions

 
GeneralExcellent work. Pin
Sachin Makwana3-Jan-16 22:55
memberSachin Makwana3-Jan-16 22:55 
GeneralRegisterViewModel with UserProfile Entity Model Pin
Member 769299321-Jul-15 18:38
memberMember 769299321-Jul-15 18:38 
GeneralRe: RegisterViewModel with UserProfile Entity Model Pin
Member 1185247126-Feb-16 0:06
memberMember 1185247126-Feb-16 0:06 
QuestionRegisterViewModels for checking if UserName Exists in MVC 5 Pin
Member 769299321-Jul-15 18:16
memberMember 769299321-Jul-15 18:16 
QuestionViewModels Pin
Member 769299321-Jul-15 18:15
memberMember 769299321-Jul-15 18:15 
Questionmethod doesn't get called Pin
sunilshetty3-Feb-15 13:57
membersunilshetty3-Feb-15 13:57 
AnswerRe: method doesn't get called Pin
Sachin Dev Tripathi6-Feb-15 2:22
professionalSachin Dev Tripathi6-Feb-15 2:22 
QuestionHow the controller's action method will be called. Pin
Member 1118320028-Dec-14 19:40
memberMember 1118320028-Dec-14 19:40 
AnswerRe: How the controller's action method will be called. Pin
Sachin Dev Tripathi28-Dec-14 20:08
professionalSachin Dev Tripathi28-Dec-14 20:08 
GeneralMy vote of 3 Pin
Wiktor Sobczyk18-Sep-14 20:20
memberWiktor Sobczyk18-Sep-14 20:20 
GeneralMy vote of 3 Pin
raha240024-Aug-14 6:08
memberraha240024-Aug-14 6:08 
GeneralMy vote of 2 Pin
Member 1017234020-Oct-13 22:14
memberMember 1017234020-Oct-13 22:14 
GeneralIn general: Pin
KChandos17-Oct-13 5:44
memberKChandos17-Oct-13 5:44 
GeneralRe: In general: Pin
Sachin Dev Tripathi17-Oct-13 19:17
professionalSachin Dev Tripathi17-Oct-13 19:17 
GeneralRe: In general: Pin
Member 1017234020-Oct-13 22:13
memberMember 1017234020-Oct-13 22:13 
GeneralRe: In general: Pin
KChandos4-Nov-13 8:45
memberKChandos4-Nov-13 8:45 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.171018.2 | Last Updated 17 Oct 2013
Article Copyright 2013 by Sachin Dev Tripathi
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid