ASP.NET MVC “Ajax.BeginForm” executes OnSuccess even though model is not valid

前端 未结 5 1037
轻奢々
轻奢々 2020-12-14 09:01

I have a \"submit feedback\" form which uses \"Ajax.BeginForm\" to render a partial containing the form elements. The OnSuccess event is triggering even if the ModelState is

5条回答
  •  -上瘾入骨i
    2020-12-14 09:58

    Is this normal?

    Yes, of course. If the server sends HTTP 200 the OnSuccess method is called. The notion of modelstate validity is server side only. As long as your controller action returns some view/partial/json/... the OnSuccess will trigger. If an exception is thrown inside your controller action then the OnError will be triggered instead of OnSuccess.

    So in order to handle this case you could have your controller action do something along the lines of:

    [HttpPost]
    public ActionResult Process(MyViewModel model)
    {
        if (!ModelState.IsValid)
        {
            return Json(new { success = false });
        }
        return Json(new { success = true });
    }
    

    and then:

    function success(result) {
        if (result.success) {
            // the model was valid
        } else {
            // the model was invalid
        }
    }
    

    Now in the case of invalid model you might want to show the error messages to the user by refreshing the form. What you could do in this case is place your form inside a partial and in the event of an invalid modelstate you would return a partialview from your controller action and in the case of success a json object. So in your success handler you could test:

    function success(result) {
        if (result.success) {
            // the model was valid
        } else {
            // there were errors => show them
            $('#myform_container').html(result);
            // if you are using client side validation you might also need
            // to take a look at the following article
            // http://weblogs.asp.net/imranbaloch/archive/2011/03/05/unobtrusive-client-side-validation-with-dynamic-contents-in-asp-net-mvc.aspx
            // and reattach the client validators to the form as you are
            // refreshing its DOM contents here
        }
    }
    

提交回复
热议问题