Thursday, 18 February 2021

MVC - Custom Validation - Remote - Validate passing additional fields (values) to the validation function

 

  Watch this example on YouTube

 

 

1. Stored Procedure

 

CREATE PROCEDURE ValidateOnDBSide
    @value int
AS
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;

    IF @value > 10
    BEGIN
        Select ''
    END
    ELSE
    BEGIN
        Select 'Error Message Retruned by Stored Procedure'
    END
END
GO 


2. Layout


<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>@ViewBag.Title - My ASP.NET Application</title>
    @Styles.Render("~/Content/css")
        @Scripts.Render("~/bundles/modernizr")
        @Scripts.Render("~/Scripts/jquery-1.12.4.min.js")
    @Scripts.Render("~/Scripts/jquery.unobtrusive-ajax.min.js")
    @Scripts.Render("~/Scripts/jquery-ui-1.12.1.min.js")
    @Scripts.Render("~/Scripts/jquery.validate.min.js")
    @Scripts.Render("~/Scripts/jquery.validate.unobtrusive.min.js")

</head>
<body>
    <div class="navbar navbar-inverse navbar-fixed-top">
        <div class="container">
            <div class="navbar-header">
                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                </button>
                @Html.ActionLink("Application name", "Index", "Home", new { area = "" }, new { @class = "navbar-brand" })
            </div>
            <div class="navbar-collapse collapse">
                <ul class="nav navbar-nav">
                    <li>@Html.ActionLink("Home", "Index", "Home")</li>
                    <li>@Html.ActionLink("About", "About", "Home")</li>
                    <li>@Html.ActionLink("Contact", "Contact", "Home")</li>
                </ul>
                @Html.Partial("_LoginPartial")
            </div>
        </div>
    </div>
    <div class="container body-content">
        @RenderBody()
        <hr />
        <footer>
            <p>&copy; @DateTime.Now.Year - My ASP.NET Application</p>
        </footer>
    </div>

    @Scripts.Render("~/bundles/jquery")
    @Scripts.Render("~/bundles/jqueryui")
    @Scripts.Render("~/bundles/jqueryval")
    @Scripts.Render("~/bundles/bootstrap")
    @RenderSection("scripts", required: false)
</body>
</html>

3. Model

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

namespace ValidateOnDbSide.Models
{
    public class Customer
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }

        [Remote(action: "ValidateSalary", controller: "Home", AdditionalFields ="FirstName,LastName",  ErrorMessage ="will never be displayed - it will display message returned by stored procedure")]
        public int Salary { get; set; }
    }
}

4. Controller

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

namespace ValidateOnDbSide.Controllers
{
    public class HomeController : Controller
    {
        CompanyEntities db = new CompanyEntities();

       

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

        [HttpPost]
        public ActionResult Index(Customer c)
        {
            if (ModelState.IsValid)
            {
                // do something here
            }
            return View(c);
        }

        [AcceptVerbs("Get", "Post")]
        public ActionResult ValidateSalary(Customer c)
        {
            string Salary = c.Salary.ToString();
            string res = db.ValidateOnDBSide(Convert.ToInt32(Salary)).FirstOrDefault();
            if(res != string.Empty)
            {
                return Json(res, JsonRequestBehavior.AllowGet);
            }
            return Json(true, JsonRequestBehavior.AllowGet);
        }


5. View

@model ValidateOnDbSide.Models.Customer

@{
    ViewBag.Title = "Home Page";
}

@{  Html.EnableClientValidation(); }
@using (Html.BeginForm(null, null, FormMethod.Post))
{
    @Html.AntiForgeryToken()
    @Html.LabelFor(x => x.FirstName)
    @Html.TextBoxFor(x => x.FirstName)
    <br />
    @Html.LabelFor(x => x.LastName)
    @Html.TextBoxFor(x => x.LastName)
    <br />

    @Html.LabelFor(x => x.Salary)
    @Html.TextBoxFor(x => x.Salary)
    @Html.ValidationMessageFor(x => x.Salary)
    <br />
    <input type="submit" value="Submit" />
}

 

 

No comments:

Post a Comment