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

推荐订阅源

博客园 - 叶小钗
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
Microsoft Security Blog
Microsoft Security Blog
罗磊的独立博客
大猫的无限游戏
大猫的无限游戏
美团技术团队
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
aimingoo的专栏
aimingoo的专栏
腾讯CDC
WordPress大学
WordPress大学
Apple Machine Learning Research
Apple Machine Learning Research
F
Fortinet All Blogs
G
Google Developers Blog
MongoDB | Blog
MongoDB | Blog
Microsoft Azure Blog
Microsoft Azure Blog
小众软件
小众软件
Engineering at Meta
Engineering at Meta
博客园_首页
B
Blog RSS Feed
D
Docker
M
MIT News - Artificial intelligence
爱范儿
爱范儿
I
InfoQ

博客园 - 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