【问题标题】:Retriving the Model state error message检索模型状态错误消息
【发布时间】:2014-09-14 11:23:51
【问题描述】:

我有以下操作方法:-

 public ActionResult AddServerToRack(AddServerToRack s)
        {

            if (ModelState.IsValid)
            {
                try
                {
                   // code goes here
                }
            }
            var errorDesc = ModelState.Select(a=>a.Value.Errors.Select(a2=>a2.ErrorMessage)).ToList();
            string desc = "";
            foreach (var i in errorDesc)
            {
                desc = desc + " " + i.ToString();
            }
            return Json(new { IsSuccess = false, description = desc}, JsonRequestBehavior.AllowGet);
        }

我想要做的是获取模型状态中的所有错误消息并将它们作为 json 对象发送。但目前我无法在我的操作方法末尾使用 foreach 获取错误消息的描述。所以任何人都可以建议,我怎样才能得到所有的模型状态错误信息描述。? 谢谢

【问题讨论】:

    标签: entity-framework entity-framework-5 asp.net-mvc-5 modelstate


    【解决方案1】:

    这对你有用:-

    foreach (ModelState modelState in ViewData.ModelState.Values) {
    string desc = "";
       foreach (ModelError error in modelState.Errors) { 
        desc = desc + " " + error.ErrorMessage.ToString();
      }
    }
    

    【讨论】:

    • 我使用 error.ErrorMessage.toString() 修改了你的代码,它起作用了,你能编辑你的答案,这样我就可以把它标记为已回答..
    【解决方案2】:

    这是一个 .Net LINQ Expression,与上面 Kartikeya Khosla 的答案相同。

      string desc = ViewData.ModelState.Values.SelectMany(modelState => 
                    modelState.Errors).Aggregate("", (current, error) => 
                    current + " " + error.ErrorMessage.ToString());
    

    【讨论】:

      猜你喜欢
      • 2011-01-09
      • 2023-03-18
      • 2018-02-24
      • 1970-01-01
      • 1970-01-01
      • 2017-10-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多