Monday, 18 December 2017

Client Side DropDownList validation in ASP.Net MVC Razor using jQuery

Client Side DropDownList validation in ASP.Net MVC Razor using jQuery

Description:

In this example we explain that how to validate DropDownList in Razor View in MVC.or client side validation for the DropDownList in MVC Razor using jQuery. Or how to perform client side validation for DropDownList in Asp.Net MVC Razor using jQuery.

Here we demonstrate that how to perform client side validation for the DropDownList using Model class and Data Annotation attributes in MVC.


Custom Validator: 

public class CheckBoxRequired : ValidationAttribute, IClientValidatable
{
    public override bool IsValid(object value)
    {
        if (value isbool)
        {
            return (bool)value;
        }

        return false;
    }

    public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
    {
        yield return new ModelClientValidationRule
        {
            ErrorMessage = FormatErrorMessage(metadata.GetDisplayName()),
            ValidationType = "checkboxrequired"
        };
    }
}

Model:

  public class EmployeeModel
    {
        [Display(Name = "I accept the above terms and conditions.")]
        [CheckBoxRequired(ErrorMessage = "Please accept the terms and condition.")]
        public bool TermsConditions { get; set; }
    }

Controller:

public class EmployeeController : Controller
    {

        // GET: Home
        public ActionResult Index()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Index(PersonModel person)
        {
            return View();
        }
    }

View:

@model DropDownList_Validation_MVC.Models.EmployeeModel

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <title>Client Side DropDownList validation in ASP.Net MVC Razor using jQuery</title>
</head>
<body>
    @using (Html.BeginForm("Index", "Employee", FormMethod.Post))
    {
        <table>
            <tr>
                <td>@Html.DisplayFor(m => m.Gender)</td>
                <td>@Html.DropDownListFor(m => m.Gender, new List<SelectListItem>
                   { new SelectListItem{Text="Male", Value="M"},
                     new SelectListItem{Text="Female", Value="F"}}, "Please select")</td>
                <td>@Html.ValidationMessageFor(m => m.Gender, "", new { @class = "error" })</td>
            </tr>
            <tr>
                <td></td>
                <td><input type="submit" value="Submit"/></td>
                <td></td>
            </tr>
        </table>
    }
</body>
@Scripts.Render("~/bundles/jquery")
@Scripts.Render("~/bundles/jqueryval")
</html>


0 comments:

Post a Comment