检索模型状态错误消息

时间:2014-07-23 10:14:43

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

我有以下行动方法: -

 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获取错误消息的描述。所以任何人都可以建议,我怎么能得到所有的模型状态错误信息描述。 感谢

2 个答案:

答案 0 :(得分:5)

这对你有用: -

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

答案 1 :(得分:1)

这是一个.Net # Importing modules import numpy as np import matplotlib.pyplot as plt g=9.81 Mmoon=7.3477e22 #mass of Moon Mearth=5.972e24 #mass of Earth R_min=356.5e6 #Perigee R_max=406.7e6 #Apogee R_avg = 0.5*(R_min + R_max) r = 6.3781e6 #radius of Earth theta=np.linspace(-1*np.pi,1*np.pi,180) a_R=3*g*(Mmoon/Mearth)*((r/(R_avg))**3)*np.cos(theta) #acceleration vector a_h=3*g*(Mmoon/Mearth)*((r/(R_avg))**3)*np.cos(theta)*np.sin(theta) #tangential acceleration vector a_r=3*g*(Mmoon/Mearth)*((r/(R_avg))**3)*np.cos(theta)*np.cos(theta) #perpendicular acceleration vector plt.quiver([0,0 ], [0,0], [2,-2], [-4, -2], angles='xy', scale_units='xy', scale=1) plt.xlim(-10,10) plt.ylim(-10,10) earth = plt.Circle((0.5, 0.5), 0.2, color='blue') # (x_pos, y_pos), rad fig, ax = plt.subplots() # note we must use plt.subplots, not plt.subplot #(or if you have an existing figure) fig = plt.gcf() ax = fig.gca() ax.add_artist(earth) ,与上面的Kartikeya Khosla的回答相同。

LINQ Expression