首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >ValidationMessage和ModelState.AddModelError不工作

ValidationMessage和ModelState.AddModelError不工作
EN

Stack Overflow用户
提问于 2014-02-11 10:26:39
回答 1查看 8K关注 0票数 1

我想要做软垫验证,并返回假和显示消息,如果验证失败。

在控制器中,下面的代码用于向数据库提交已发布的数据。

代码语言:javascript
复制
       [HttpPost]
       public JsonResult SubmitDa(IList<AdViewModel> s, String section)
           {

            ...........
              ..........


            ModelState.AddModelError("MessageError", "Please enter AttendanceDate");

             JSONSubmit r = new JSONSubmit();
            r.ErrorCount = iError;
            r.errors = errors;

           return Json(r, JsonRequestBehavior.AllowGet);

       }

下面是视图文件中的代码(cshtml)

代码语言:javascript
复制
       @Html.ValidationMessage("MessageError")  
        .....  

       $.AJAX call to `SubmitDa` controller's method.

消息没有出现在"MessageError“验证消息中。请告诉我这里出了什么问题。

谢谢

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-02-11 11:07:16

如果您想要使用模型状态来处理错误,就不应该真正发送JSON响应。尽管如此,您可以通过让控制器只在成功的情况下返回JSON来处理它,并且页面处理响应的方式不同

IE:

代码语言:javascript
复制
[HttpPost]
public ActionResult SubmitDa(IList<AdViewModel> s, String section)
{

        ...........
          ..........


        ModelState.AddModelError("MessageError", "Please enter AttendanceDate");

         JSONSubmit r = new JSONSubmit();
        r.ErrorCount = iError;
        r.errors = errors;
       if (r.ErrorCount != 0)
           return Json(r, JsonRequestBehavior.AllowGet);

       return View("ViewName", s); // <-- just return the model again to the view,
                                   //     complete with modelstate!
}

在页面上,如下所示:

代码语言:javascript
复制
<script>

$("#buttonId").click({
   $.ajax({
     type: "POST",
     url: "PostBackURL",
     data: $("#formID").serialize(),
     success: function (response){
       //test for a property in the JSON response
       if(response.ErrorCount && response.ErrorCount == 0) 
       {
           //success! do whatever else you want with the response

       } else {
          //fail - replace the HTML with the returned response HTML.
          var newDoc = document.open("text/html", "replace");
          newDoc.write(response);
          newDoc.close();
       }

     }
   });
});

</script>
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/21699193

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档