ASP.NET MVC 5 Model Validation

Explicitly Validating a Model

        [HttpPost]
        public ViewResult MakeBooking(Appointment appt)
        {
            if (string.IsNullOrEmpty(appt.ClientName))
            {
                ModelState.AddModelError("ClientName", "Please enter your name");
            }
            if (ModelState.IsValidField("Date") && DateTime.Now > appt.Date)
            {
                ModelState.AddModelError("Date", "Please enter a future date");
            }
            if (!appt.TermsAccepted)
            {
                ModelState.AddModelError("TermsAccepted", "You must accept the terms");
            }

            if (ModelState.IsValid)
            {
                // Statement to store new appointment in a repository would go here in real project 

                return View("Completed", appt);
            }
            else
            {
                return View();
            }
        }

Displaying Validation Errors to the User

The helpers add a CSS class called "input-validation-error" to the input elements if an error has been reported for the corresponding properties

Displaying Validation Messages (Error CSS class used is "validation-summary-errors")

@model ModelValidation.Models.Appointment

@{
    ViewBag.Title = "Make an Appointment";
}

<h2>Make an Appointment</h2>
@using (Html.BeginForm())
{
    @Html.ValidationSummary()
    <p>Your name: @Html.EditorFor(m => m.ClientName)</p>
    <p>Appointment Date: @Html.EditorFor(m => m.Date)</p>
    <p>@Html.EditorFor(m => m.TermsAccepted) I accept the terms & conditions</p>
    <input type="submit" value="Make Booking" />
}

Displaying Property-Level Validation Messages (Error CSS class used is "field-validation-error")

@model ModelValidation.Models.Appointment

@{
    ViewBag.Title = "Make an Appointment";
}

<h2>Make an Appointment</h2>
@using (Html.BeginForm())
{
    @Html.ValidationSummary(true)
    <p>@Html.ValidationMessageFor(m => m.ClientName)</p>
    <p>Your name: @Html.EditorFor(m => m.ClientName)</p>
    <p>@Html.ValidationMessageFor(m => m.Date)</p>
    <p>Appointment Date: @Html.EditorFor(m => m.Date)</p>
    <p>@Html.ValidationMessageFor(m => m.TermsAccepted)</p>
    <p>@Html.EditorFor(m => m.TermsAccepted) I accept the terms & conditions</p>
    <input type="submit" value="Make Booking" />
}

Performing Validation in the Model Binder

The default model binder performs validation as part of the binding process. The model binder performs basic validation for each of the properties in the model object. The built-in default model binder class, DefaultModelBinder, provides some useful methods that can be overridden to add validation to a binder.

Specifying Validation Rules Using Metadata

The advantage of using metadata is that the validation rules are enforced anywhere that the binding process is applied throughout the application, not just in a single action method. The validation attributes are detected and enforced by the built-in default model binder class, DefaultModelBinder.

    public class Appointment
    {
        [Required]
        public string ClientName { get; set; }

        [DataType(DataType.Date)]
        [Required(ErrorMessage="Please enter a date")]
        public DateTime Date { get; set; }

        [Range(typeof(bool),"true","true",ErrorMessage="You must accept the terms")]
        public bool TermsAccepted { get; set; }
    }

Creating a Custom Property Validation Attribute

I can also create my own by deriving from the ValidationAttribute class and implementing custom validation logic.

    public class MustBeTrueAttribute: ValidationAttribute
    {
        public override bool IsValid(object value)
        {
            return value is bool && (bool)value;
        }
    }

Deriving from the Built-In Validation Attributes

    public class FutureDateAttribute:RequiredAttribute
    {
        public override bool IsValid(object value)
        {
            return base.IsValid(value) && ((DateTime)value) > DateTime.Now;
        }
    }

Creating a Model Validation Attribute

    public class NoJoeOnMondaysAttribute: ValidationAttribute
    {
        public NoJoeOnMondaysAttribute() {
            ErrorMessage = "Joe cannot book appointments on Mondays";
        }

        public override bool IsValid(object value)
        {
            Appointment app = value as Appointment;
            if (app == null || string.IsNullOrEmpty(app.ClientName) || app.Date == null)
            {
                // I don‘t have a model of right type to validate, or I don‘t have the values for ClientName or Date properties I require
                return true;
            }
            else
            {
                return !(app.ClientName == "Joe" && app.Date.DayOfWeek == DayOfWeek.Monday);
            }
        }
    }

Defining Self-Validating Models

Another validation technique is to create self-validating models, where the validation logic is part of the model class. A self-validating model implements the IValidatableObject interface.

Performing Client-Side Validation

The MVC Framework supports unobtrusive client-side validation. The term unobtrusive means that validation rules are expressed using attributes added to the HTML elements that views generate. These attributes are interpreted by a JavaScript library that is included as part of the MVC Framework that, in turn, configures the jQuery Validation library, which does the actual validation work.

Enabling Client-Side Validation

Client-side validation is controlled by two settings in the Web.config file.

<appSettings>
    <add key="webpages:Version" value="3.0.0.0" />
    <add key="webpages:Enabled" value="false" />
    <add key="ClientValidationEnabled" value="true" />
    <add key="UnobtrusiveJavaScriptEnabled" value="true" />
</appSettings>

You can also configure client-side validation on a per-view basis by setting the HtmlHelper.ClientValidationEnabled and HtmlHelper.UnobtrusiveJavaScriptEnabled in a Razor code block.

Adding the NuGet Packages

Install-Package jQuery –version 1.10.2
Install-Package jQuery.Validation –version 1.11.1
Install-Package Microsoft.jQuery.Unobtrusive.Validation –version 3.0.0

Using Client-Side Validation

Firstly you need to add the javascript liabaries to the _Layout.cshtml page, then apply the metadata attributes that I previously used for server-side validation, such as Required, Range, and StringLength to model.

Performing Remote Validation

This is a client-side validation technique that invokes an action method on the server to perform validation.(A common example of remote validation is to check whether a username is available in applications when such names must be unique)

The first step toward using remote validation is to create an action method that can validate one of the model properties. Action method must return JsonResult type. (The MVC Framework disallows GET requests that produce JSON by default)

        public JsonResult ValidateDate(string Date)
        {
            DateTime parsedDate;
            if (!DateTime.TryParse(Date, out parsedDate))
            {
                return Json("Please enter a valid date", JsonRequestBehavior.AllowGet);
            }
            else if (parsedDate < DateTime.Now)
            {
                return Json("Please enter a date in the future", JsonRequestBehavior.AllowGet);
            }
            else
            {
                return Json(true, JsonRequestBehavior.AllowGet);
            }
        }

To use the remote validation method, I apply the Remote attribute to the property I want to validate in the model class.

时间: 2024-12-14 03:09:59

ASP.NET MVC 5 Model Validation的相关文章

ASP.NET MVC中Model相关技术

在Model里的程序,由于“只能”跟数据与商业逻辑有关,因此Model专注于如何有效地提供数据访问机制.交易环境.数据格式.商业逻辑验证等工作. 一.使用Code First创建数据模型 数据库开发模式有数据库优先开发模式(Database First Development).模型优先开发模式(Model First Development)和程序代码优先开发模式(Code First Development)这三种.ASP.NET MVC的Model数据库开发模式为程序代码优先开发模式,使用

ASP.NET MVC传递Model到视图的多种方式总结

ASP.NET MVC传递Model到视图的多种方式总结 有多种方式可以将数据传递到视图,如下所示: ViewData ViewBag PartialView TempData ViewModel Tuple 场景: 在视图页面,下拉框选择课程触发事件,分别显示老师课程表.学生上课表,如图: 相关的Model: 1 public class Course 2 { 3 public int Id { get; set; } 4 public string Name { get; set; } 5

ASP.NET MVC传递Model到视图的多种方式之通用方式的使用

ASP.NET MVC传递Model到视图的多种方式总结——通用方式的使用 有多种方式可以将数据传递到视图,如下所示: ViewData ViewBag PartialView TempData ViewModel Tuple 场景: 在视图页面,下拉框选择课程触发事件,分别显示老师课程表.学生上课表,如图: ? 相关的Model: 1 public class Course 2 { 3 public int Id { get; set; } 4 public string Name { get

ASP.NET MVC中Model元数据解析学习

闲来继续学习蒋金楠大师的ASP.NET MVC框架揭秘一书,当前主要阅读的内容是Model元数据的解析,即使是阅读完的现在,仍然有不少细节不是特别明白.好在这部分内容主要是关于Razor引擎的呈现的,通过注解的方式对Model进行自定的修饰,最终使得页面在渲染时(即从cshtml文件转化为html时),相关的数据能够按照指定的形式转化并显示.由于接下来的项目中不再打算使用Razor引擎,该引擎虽然很不错,但也有一些问题,例如存在HTML5代码与HtmlHelper的混写,使得UI层很难与业务代码

仅此一文让你明白ASP.NET MVC 之Model的呈现

本文目的 我们来看一个小例子,在一个ASP.NET MVC项目中创建一个控制器Home,只有一个Index: public class HomeController : Controller { public ActionResult Index() { var model = new DemoModel {Email = "[email protected]"}; return View(model); } } public class DemoModel { [DataType(D

asp.net mvc 提交model 接收不了

[HttpPost]        //[ValidateInput(false)]        public ActionResult AddNews1(_54Young_News_Model.model.gou54contentall contentmodel, _54Young_News_Model.model.gou54user usermodel)        {} 发现用一些特殊符号提交不了, 然后以为说前端问题,把model去掉就可以了. 后面觉得是因为有特殊符号影响到转mod

ASP.NET MVC - loop model data in javascript

Key: razor syntax using @: before the js variable in c# code block Example: var chartData = []; @for(int i=0; i < Model.ModuleDetails.Count; i++) { @: chartData.push(@Html.Raw(Json.Encode(Model.ModuleDetails[i].ChartData.ToArray()))); } reference: ht

简易留言薄系统-ASP.NET MVC(Model层)

我的开发顺序是从Model层开始.在Model层目前一共有4个类.Model层除MvcBbsContext引用了System.componentModel 与 System.ComponentModel.DataAnnotations,在MvcBbsContext类中引用了System.Data.Entity 1.User 代码: using System;using System.Collections.Generic;using System.Linq;using System.Web;us

ASP.NET MVC 5 Model Binding

Default Model Binder The Order in Which the DefaultModelBinder Class Looks for Parameter Data: Request.Form - Values provided by the user in HTML form elements RouteData.Values - The values obtained using the application routes Request.QueryString -