惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Microsoft Azure Blog
Microsoft Azure Blog
GbyAI
GbyAI
P
Proofpoint News Feed
Engineering at Meta
Engineering at Meta
Recent Announcements
Recent Announcements
L
LangChain Blog
B
Blog
阮一峰的网络日志
阮一峰的网络日志
Microsoft Security Blog
Microsoft Security Blog
博客园 - 【当耐特】
M
MIT News - Artificial intelligence
D
Docker
WordPress大学
WordPress大学
J
Java Code Geeks
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
The GitHub Blog
The GitHub Blog
博客园 - 叶小钗
Last Week in AI
Last Week in AI
Stack Overflow Blog
Stack Overflow Blog
有赞技术团队
有赞技术团队
MyScale Blog
MyScale Blog
H
Hackread – Cybersecurity News, Data Breaches, AI and More
MongoDB | Blog
MongoDB | Blog
博客园 - Franky

博客园 - andyran

xp下多站点及asp.net mvc3配置 CSS line-height:XX在IE7下面与IE6、IE8、FireFox高度不一样 HRESULT:0x80070057 (E_INVALIDARG)的异常的解决方案 css中div高度自适应的方法(兼容FF IE) Win7安装SQL2005的IIS7设置 CSS兼容与标准,HACK技巧 - andyran - 博客园 通过jquery选择li菜单实现无刷新css效果 - andyran - 博客园 .NET打包安装MSDE以及安装和卸载 为FCKEDITOR添加导入Word文档功能 PEAR之DB_DataObject快速安装 c#实现随鼠标移动窗体 SVN使用技巧 - 不要把不必要的文件版本化 svn架设快速入门(转) utf8的bom问题 Flex中的拖放(Drag-Drop)事件入门 续:使用FLEX为上传的图片添加水印 使用FLEX实现简单WEB在线拍照功能 使用jQuery编写一个UBB编辑器 编写jQuery插件来扩展checkbox
获取Controller.ModelState中的所有错误信息
andyran · 2011-11-02 · via 博客园 - andyran

利用MVC的实体验证框架,AJAX提交,返回错误信息。

扩展方法实现

public static class ModelStateExtensions
{
    public static string ExpendErrors(this System.Web.Mvc.Controller controller)
    {
        System.Text.StringBuilder sbErrors = new System.Text.StringBuilder();
        foreach (var item in controller.ModelState.Values)
        {
            if (item.Errors.Count > 0)
            {
                for (int i = item.Errors.Count - 1; i >= 0; i--)
                {
                    sbErrors.Append(item.Errors[i].ErrorMessage);
                    sbErrors.Append("<br/>");
                }
            }
        }
        return sbErrors.ToString();
    }
}

//Linq版,效率不如循环遍历,有待优化
public static string ExpendErrors2(this Controller controller)
{
    System.Text.StringBuilder sbError = new System.Text.StringBuilder();
    (from key in controller.ModelState.Keys
     where controller.ModelState[key].Errors.Count > 0
     select key)
     .Aggregate(sbError, (sb, key) =>
        {
            return controller.ModelState[key].Errors
                .Aggregate(sb, (sbChild, error) => sbChild.AppendFormat("{0}<br/>", error.ErrorMessage));
        });
    return sbError.ToString();
}

//调用
if (ModelState.IsValid)
{
    //do something
    return Content("0");
}
else
{
    return Content(this.ExpendErrors());
}

原文:http://www.cnblogs.com/eyu/archive/2011/01/23/1942291.html