ModelStateExtensions.cs

using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc; namespace MvcSample.Extensions
{
public static class ModelStateExtensions
{
private static string GetErrorMessage(ModelError error, ModelState modelState)
{
if (!string.IsNullOrEmpty(error.ErrorMessage))
{
return error.ErrorMessage;
}
if (modelState.Value == null)
{
return error.ErrorMessage;
}
var args = new object[] { modelState.Value.AttemptedValue };
return string.Format("属性的值不合法=值 '{0}' 非法!", args);
} public static object SerializeErrors(this ModelStateDictionary modelState)
{
return modelState.Where(entry => entry.Value.Errors.Any())
.ToDictionary(entry => entry.Key, entry => SerializeModelState(entry.Value));
} private static Dictionary<string, object> SerializeModelState(ModelState modelState)
{
var dictionary = new Dictionary<string, object>();
dictionary["errors"] = modelState.Errors.Select(x => GetErrorMessage(x, modelState)).ToArray();
return dictionary;
} public static object ToDataSourceResult(this ModelStateDictionary modelState)
{
if (!modelState.IsValid)
{
return modelState.SerializeErrors();
}
return null;
}
}
}

控制器

        [HttpPost]
public ActionResult ModifyProduct(ProductInfoModifyViewModel viewModel,
[ModelBinder(typeof(CommaSeparatedModelBinder))] List<int> orderStatusIds = null)
{
if (!ModelState.IsValid)
{
return Json(new DataSourceResult { Errors = ModelState.SerializeErrors() });
}
ProductInfoService.TryModifyById(viewModel.ProductId, viewModel.NewYear);
return Json(new { Success = true, Message = "保存成功" });
}

DataSourceResult

    public class DataSourceResult
{
public object ExtraData { get; set; } public IEnumerable Data { get; set; } public object Errors { get; set; } public int Total { get; set; }
}

前端(HTML)调用

        jQuery.ajax({
type: "POST",
url: "@Url.Action("ModifyProduct")",
//data: { productId: productId, newYear: nowValue, orderStatusIds: "1,2,3,4", ProductName: " abc d e " }, //
data: { productId: , ProductName: "" }, //
success: function (data) {
alert(data.Message);
jObj.attr("old-value", nowValue);
},
error: function (xmlHttpRequest, textStatus, errorThrown) {
alert(textStatus);
}
});

ProductInfoModifyViewModel.cs

using MvcSample.Extensions;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web; namespace MvcSample.Models
{
public class ProductInfoModifyViewModel : BaseSkyViewModel
{
[Required]
[Range(, int.MaxValue, ErrorMessage = "产品 ID 必须大于 0")]
public int ProductId { get; set; } /// <summary>
/// 假设有一个这个 Property
/// </summary>
[Display(Name = "产品名称")]
[Required(ErrorMessage = "{0}不能为空!")]
[StringLength(, MinimumLength = , ErrorMessage = "{0}的长度必须在 {2} 和 {1} 之间")] //产品名称的长度必须在 1 和 30 之间
public string ProductName { get; set; } public int NewYear { get; set; }
}
}

运行效果:

{
"ExtraData": null,
"Data": null,
"Errors": {
"ProductId": {
"errors": ["产品 ID 必须大于 0"]
},
"ProductName": {
"errors": ["产品名称不能为空!"]
}
},
"Total":
}

谢谢浏览!

ASP.NET MVC 下自定义 ModelState 扩展类,响应给 AJAX的更多相关文章

  1. ASP.NET MVC下自定义错误页和展示错误页的几种方式

    在网站运行中,错误是不可避免的,错误页的产生也是不可缺少的. 这几天看了博友的很多文章,自己想总结下我从中学到的和实际中配置的. 首先,需要知道产生错误页的来源,一种是我们的.NET平台抛出的,一种是 ...

  2. ASP.NET MVC 下自定义模型绑定,去除字符串类型前后的空格

    直接贴代码了: SkyModelBinder.cs using System.ComponentModel; using System.Linq; using System.Web.Mvc; name ...

  3. ASP.NET MVC 下自定义 JsonResult,使用 Json.NET 序列化 JSON

    直接贴代码了: using System; using System.Web.Mvc; using Newtonsoft.Json; namespace MvcSample.Extensions { ...

  4. Response.End()在Webform和ASP.NET MVC下的表现差异

    前几天在博问中看到一个问题--Response.End()后,是否停止执行?MVC与WebForm不一致.看到LZ的描述后,虽然奇怪于为何用Response.End()而不用return方式去控制流程 ...

  5. ASP.NET MVC下的四种验证编程方式

    ASP.NET MVC采用Model绑定为目标Action生成了相应的参数列表,但是在真正执行目标Action方法之前,还需要对绑定的参数实施验证以确保其有效性,我们将针对参数的验证成为Model绑定 ...

  6. ASP.NET MVC下的四种验证编程方式【转】

    ASP.NET MVC采用Model绑定为目标Action生成了相应的参数列表,但是在真正执行目标Action方法之前,还需要对绑定的参数实施验证以确保其有效 性,我们将针对参数的验证成为Model绑 ...

  7. 转:【译】Asp.net MVC 利用自定义RouteHandler来防止图片盗链

    [译]Asp.net MVC 利用自定义RouteHandler来防止图片盗链   你曾经注意过在你服务器请求日志中多了很多对图片资源的请求吗?这可能是有人在他们的网站中盗链了你的图片所致,这会占用你 ...

  8. ASP.NET MVC学前篇之扩展方法、链式编程

    ASP.NET MVC学前篇之扩展方法.链式编程 前言 目的没有别的,就是介绍几点在ASP.NETMVC 用到C#语言特性,还有一些其他琐碎的知识点,强行的划分一个范围的话,只能说都跟MVC有关,有的 ...

  9. Asp.Net MVC以 JSON传值扩展方法

    Asp.Net在客户端和服务器端,以JSON形式相互传值,可写扩展方法,用到的类型如下: DataContractJsonSerializer类: 该类在System.Runtime.Serializ ...

随机推荐

  1. WinServer设置多用户登录

    1.运行 gpedit.msc →computer configuration→administrative templates→windows componets→Remote Desktop→Re ...

  2. CAP 2.4版本发布,支持版本隔离特性

    前言 自从上次 CAP 2.3 版本发布 以来,已经过去了几个月的时间,这几个月比较忙,所以也没有怎么写博客,趁着2019年到来之际(现在应该是2019年开始的时候),CAP也发布了2018年的最后一 ...

  3. C#常见金额优选类型及其三种常用的取整方式

    这两天一直在做一个商城后台的对账方面的工作,忽然发现C#真的有很多值的学习的东西: 一.C#常用的三种取整方式(主要适用于double.decimal.float这一类型的数据): Math.Roun ...

  4. class基本使用

    console.log(` 1.创建一个空对象 2.让this 指向刚刚创建好的空对象 3.执行构造函数内的代码 (为相关的属性和方法赋值) 4.返回创建好的对象`) // 1.创建一个空对象 // ...

  5. 吴恩达机器学习笔记61-应用实例:图片文字识别(Application Example: Photo OCR)【完结】

    最后一章内容,主要是OCR的实例,很多都是和经验或者实际应用有关:看完了,总之,善始善终,继续加油!! 一.图像识别(店名识别)的步骤: 图像文字识别应用所作的事是,从一张给定的图片中识别文字.这比从 ...

  6. 使用Update Strategy组件无法进行delete操作

    问题: Update Strategy组件根据字段值对目标表进行DD_DELETE操作时失效 同时,session log中报错:Target table [XXXXXXXX] does not al ...

  7. 1. 容器化部署一套云服务 第一讲 Jenkins(Docker + Jenkins + Yii2 + 云服务器))

    容器化部署一套云服务系列 1. 容器化部署一套云服务之Jenkins 一.购买服务器 服务器

  8. Data Warehouse

    Knowledge Discovery Process OLTP & OLAP 联机事务处理(OLTP, online transactional processing)系统:涵盖组织机构大部 ...

  9. 【ASP.NET Core快速入门】(三)准备CentOS和Nginx环境

    基本软件 VMware虚拟机 centos:http://isoredirect.centos.org/centos/7/isos/x86_64/CentOS-7-x86_64-Minimal-170 ...

  10. SmartSql Map

    SmartSqlMap 属性 说明 Scope 域,用于SqlMap定义Sql声明范围 Statement标签 属性 说明 Id 唯一性编号 Cache 缓存策略编号,引用自Cache标签 State ...