• Implementing Remote Validation in MVC


    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;
                 100%;
                padding: 10px;
            }
            .row label
            {
                 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.  

  • 相关阅读:
    jquery选择器
    jquery是方便了javascript,算是其子,导入方式必须记住,js文件自己官网下载
    checkbox操作全选、反选、取消
    onsubmit事件、事件传播判定函数stoppropagetion、事件使用2种方式
    onload函数绑定,byclass数组遍历、this获取整个标签内容
    区分byid和byclass的取值方法关键是有无数组、onfocus和onblur
    dom :document、element,如何取父标签和子标签,innertext获取标签内容
    定时器,setInterval、clearInterval
    一个简单css+js的开关组件
    Bootstrap 模态框强化
  • 原文地址:https://www.cnblogs.com/Alex80/p/4710920.html
Copyright © 2020-2023  润新知