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. 从壹开始前后端分离【 .NET Core2.0 +Vue2.0 】框架之六 || API项目整体搭建 6.1 仓储模式

    前言 1.@LearningCoding 小伙伴关于用Sqlsugar在mysql数据库上的研究成果: sqlsugarcore支持mysql等数据库,在DbContext里面只需要设置dbtype为 ...

  2. SQL优化 MySQL版 - 避免索引失效原则(一)

    避免索引失效原则(一) 精力有限,剩余的失效原则将会在 <避免索引失效原则(二)>中连载出来,请谅解 作者 : Stanley 罗昊 [转载请注明出处和署名,谢谢!] 避免索引失效的一些原 ...

  3. .Net Core的Log方式:Serilog+Kibana

    前言 Serilog,支持对象,把log数据序列化成Json,好用方便,容易拓展.Github: https://github.com/handsomeyao77/serilog-sinks-elas ...

  4. Golang struct结构

    结构struct Go中的struct与C中的struct非常相似,并且Go没有class,代替了class的位置,但并没有代替class的功能 使用type struct{} 定义结构,名称遵循可见 ...

  5. nginx系列8:反向代理和负载均衡原理

    反向代理是nginx的一个非常重要的功能. 反向代理 nginx支持四层反向代理和七层反向代理,如下图. 负载均衡 负载均衡是实现服务高性能和高可用的重要手段,而nginx是实现负载均衡的重要工具.

  6. CentOS7 firewalld 打开关闭端口

    1. firewalld的基本使用 启动: systemctl start firewalld 关闭: systemctl stop firewalld 查看状态: systemctl status ...

  7. 使用VC建立网络连接并访问网络资源

    目录 1. 提出问题 2. 解决方案 1. 提出问题 在windows下可以通过系统操作,将局域网的资源映射到本地,从而实现像本地数据一样访问网络资源.实际上这些步骤也可通过代码调用win32函数实现 ...

  8. git 提交项目代码到码云步骤 以及出现错误解决办法

    git initgit remote add origin 项目地址git add .git commit -m "注释"git push origin master 出现错误 $ ...

  9. Windows Azure NotificationHub+Firebase Cloud Message 实现消息推动(付源码)

    前期项目一直用的是Windows azure NotificationHub+Google Cloud Message 实现消息推送, 但是GCM google已经不再推荐使用,慢慢就不再维护了, 现 ...

  10. springboot集成elasticsearch

    在基础阶段学习ES一般是首先是 安装ES后借助 Kibana 来进行CURD 了解ES的使用: 在进阶阶段可以需要学习ES的底层原理,如何通过Version来实现乐观锁保证ES不出问题等核心原理: 第 ...