MVC 4 Ajax.BeginForm和ModelState.AddModelError [英] MVC 4 Ajax.BeginForm and ModelState.AddModelError

查看:109
本文介绍了MVC 4 Ajax.BeginForm和ModelState.AddModelError的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在ajax提交返回错误后显示错误.我不确定我缺少什么,但是我无法使它正常工作.这个问题基本上是同一回事- ModelState.AddModelError不是显示在我的视图中,但我仍然没有运气.我对Ajax和MVC(任何版本)的经验仍然有限.这是一个非常简单的示例,其中大部分是我从上一个链接中获得的.

I'm trying to get errors to show up after an ajax submit has returned an error. I'm not sure what I'm missing, but I can't get it to work. This question is basically the same thing - ModelState.AddModelError is not being displayed inside my view but I'm still not having any luck. My experience with Ajax and MVC (any version) is still a bit limited. Here is a very simple example, most of which I took from the previous link.

查看:test.cshtml

View: test.cshtml

@model TestProject.VisitLabResult

@Scripts.Render("~/Scripts/jquery.unobtrusive-ajax.min.js")
@Scripts.Render("~/Scripts/ckeditor/ckeditor.js")

@{
    AjaxOptions ajaxOpts = new AjaxOptions
    {
        Url = Url.Action("test"),
        HttpMethod = "Post",
        LoadingElementId = "loading",
        LoadingElementDuration = 500,
        OnSuccess = "processData"
    };
}
@Html.ValidationMessage("CustomError")


<div id="loading" class="load" style="display:none">
    <p>Saving...</p>
</div>

<table>
@for (int item = 0; item < 10; item++)
{
    <tr id = @item>
    @using (Ajax.BeginForm(ajaxOpts))
    {  
        @Html.ValidationSummary(true)

        @Html.AntiForgeryToken()

        <td>
            <input type="submit" value="Create" />
        </td>

        <td id = @(item.ToString() + "td")>
        </td>
    }
    </tr>
    }
</table>

控制器:HomeController.cs

Controller: HomeController.cs

public ActionResult test()
{
    return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult test(VisitLabResult vlr, int visitid = 28)
{
    try
    {
        if (ModelState.IsValid)
        {
            if (Request.IsAjaxRequest())
            {
                throw new Exception("error");
            }
            else
                return View(vlr);
        }
        else
            return View(vlr);
    }
    catch (Exception ex)
    {
        ModelState.AddModelError("CustomError", "The Same test Type might have been already created, go back to the Visit page to see the available Lab Tests");
        return View(vlr);
    }
}

模型

public class VisitLabResult
{
    public int visitid { get; set; }
}

如果这是一个Ajax请求,我抛出一个错误并被捕获,并且一个错误被添加到ModelState中.该错误永远不会显示在页面上.我是否完全以这种正确的方式来对待?还是我需要采取其他路线?感谢您的帮助.

If it is an Ajax request I throw an error and it's caught and an error is added to ModelState. That error never shows up on the page though. Am I approaching this the right way at all? Or do I need to take a different route? I appreciate any help.

推荐答案

只是为了澄清其他遇到此问题的人的解决方案.根据OnSuccess与OnFailure. aspx"rel =" nofollow noreferrer> AjaxOptions文档:

Just to clarify the solution for other people hitting this question. The ajax helper fires OnSuccess vs OnFailure based on the returned HTTP Code per the AjaxOptions docs:

OnSuccess a>:如果响应状态 在200范围内,则会调用此函数.
OnFailure :如果响应状态不在在200范围内,则调用此函数.

OnSuccess: This function is called if the response status is in the 200 range.
OnFailure: This function is called if the response status is not in the 200 range.

换句话说,您必须通过更改Response.StatusCode然后返回OnFailure js方法中期望的任何值来手动指定返回ActionResult时失败.您可以根据需要的任何业务逻辑(例如catch Exception ex)!ModelState.IsValid ...)

In other words, you have to manually specify that there was a failure when returning your ActionResult by changing the Response.StatusCode and then returning whatever values you're expecting in your OnFailure js method. You can drive that based on any business logic you want (i.e. catch Exception ex) or !ModelState.IsValid ...)

[HttpPost]
public ActionResult Search(Person model) 
{
  if (ModelState.IsValid) {
    // if valid, return a HTML view inserted by AJAX helper
    var results = PersonRepository.Get(model)
    return PartialView("Resulsts", vm);

  } else {
    // if invalid, return a JSON object and handle with OnFailure method
    Response.StatusCode = (int)HttpStatusCode.BadRequest;
    return Json(new { errors = ModelState.Values.SelectMany(v => v.Errors) });

  }
}

进一步阅读:

  • MVC 4 Ajax.BeginForm and ModelState.AddModelError
  • ASP.NET MVC "Ajax.BeginForm" executes OnSuccess even though model is not valid

这篇关于MVC 4 Ajax.BeginForm和ModelState.AddModelError的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆