C# .NET MVC3 ModelState.IsValid
我使用 JSON 从表单发布数据,ModelState.isValid() 返回 false,我为所有传入数据放置了一个 WriteLine,一切看起来都很好,有没有办法显示模型状态错误以找出未验证的内容? 这个确切的代码适用于其他模型,
[HttpPost]
public ActionResult mobileCreateAction(Trip trip)
{
if (ModelState.IsValid)
{
System.Diagnostics.Debug.WriteLine("saving");
DB.Trips.Add(trip);
DB.SaveChanges();
return Json(new
{
success = true,
msg = "Success saving trip"
});
}
else
{
System.Diagnostics.Debug.WriteLine("invalid model state");
return Json(new
{
success = false,
msg = "Error saving trip"
}, JsonRequestBehavior.AllowGet);
}
}
谢谢
Im using JSON to post data from a form and ModelState.isValid() returning false, i put a WriteLine for all incoming data and everything looks fine data wise, is there a way to display model state errors to figure out what is not validating?
this exact code works fine with other models
[HttpPost]
public ActionResult mobileCreateAction(Trip trip)
{
if (ModelState.IsValid)
{
System.Diagnostics.Debug.WriteLine("saving");
DB.Trips.Add(trip);
DB.SaveChanges();
return Json(new
{
success = true,
msg = "Success saving trip"
});
}
else
{
System.Diagnostics.Debug.WriteLine("invalid model state");
return Json(new
{
success = false,
msg = "Error saving trip"
}, JsonRequestBehavior.AllowGet);
}
}
thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以在 ModelState.Values 集合中找到错误。每个值都有一个 Errors 集合,其中包含该属性的所有模型错误。
You can find the errors in the ModelState.Values collection. Every value has an Errors collection that contains all the model errors for that property.
SO Post
基于@Darin 的回答上面链接的帖子提供了显示“原因”消息所需的代码。
SO Post
Building on @Darin's answer the post linked above provides the code needed to display the 'why' message.
要获取模型状态中的错误列表:
然后在此行上放置一个断点并检查
errors
变量。它将为您提供模型的属性列表及其各自的错误。To get a list of errors in the model state:
Then put a break point on this line and inspect the
errors
variable. It will give you a list of properties on your model with their respective errors.