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

前端 未结 5 1042
轻奢々
轻奢々 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条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-14 10:00

    I return a bad request instead of the View to ensure that the ajax call returns onfail and not onsuccess.

    In the xhr.statustext you can find the string written in the bad request and manage correctly the onfail event.

    Server side:

    if (!ModelState.IsValid)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest, "Model not valid");
            }
    

    Client side:

    $.ajax({
            url: '',
            method: 'POST'            
           }).fail(function (xhr) {
               alert(xhr.statustext);
           });
    

提交回复
热议问题