通过jQuery Ajax在Web Api中显示无效的ModelState [英] displaying invalid ModelState in Web Api via jquery ajax

查看:105
本文介绍了通过jQuery Ajax在Web Api中显示无效的ModelState的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将Web Api与Knockoutjs一起使用.我试图弄清楚如何将无效模型状态的详细信息返回给用户.

I am using Web Api with Knockoutjs. I am trying to figure out how to get the details of the invalid model state back to the user.

这是在VB中,我是如此非常抱歉,这不是我的错!!! (请允许我给我很多减分,因为我了解vb)

this is in VB I am so so so sorry it is not my fault!!! (feel free to give me many minus points for this being in vb I understand)

好,我们走了

所以我在模型上放了一个必填字段.

so I put a required field on my model.

 <Required>
    Public Property test() As String
        Get
            Return m_test
        End Get
        Set(value As String)
            m_test = value
        End Set
    End Property
    Private m_test As String

在控制器中,我具有保存功能.

in the controller I have my save function.

<HttpPost>
    Public Async Function Save(data As Origin_SingleOvrUndr_main_rewrite_vm) As Task(Of IHttpActionResult)
        If ModelState.IsValid Then
            Await Origin_SingleOvrUndr_main_rewrite_vmRepository.SaveDataAsync(data)
            Return Ok()
        Else
            Return BadRequest(ModelState)
        End If
    End Function

在我的html页面上,我调用保存.

and on my html page I am calling the save.

this.saveData = function () {
                var data = ko.toJSON(self);
                $.ajax({
                    url: "api/VMOriginSingleOvrUndrMainRewrite",
                    type: "POST",
                    data: data,
                    datatype: "json",
                    processData: false,
                    contentType: "application/json; charset=utf-8",
                    success: function (result) {
                        alert('save successfull');
                    },
                    error: function (xhr, status, error) { 
                        var err = eval("(" + xhr.responseText + ")");
                        alert(err.Message);

                    },
                });
            }

所以我故意在帖子上省略了必填字段,以查看响应是什么.因此响应是(通过点击F12并查看IE11中的响应正文)

so I purposely left out the required field on the post to see what the response would be. so the response is (by hitting F12 and looking at the response body in IE11)

{"Message":"The request is invalid.","ModelState":{"data.test":["The test field is required."]}}

但是仅显示网页上的警报.消息(请求无效).

however the alert on the web page just displays. the Message (The Request is invalid).

如何在jquery ajax错误部分中让警报显示有关测试字段的部分? (以及其中可能还有其他消息吗?)

how, in the jquery ajax error section can I have the alert display the part about the test field is required? (and any other messages that might be in there?)

推荐答案

您可以使用显示在您的ko视图上的名为errorsobservableArray.

You can use an observableArray called errors, displayed on you ko view.

这里是一个片段,其中的视图和模型与错误相对应.它采用原始响应,提取错误,然后在视图中显示它们:

Here is an snippet with the view and model corresponding to errors. It takes the original response, extract the errors, and show them in the view:

<div class="errors" data-bind="foreach: errors">
   <div>
     <p data-bind="text:prop"></p>
     <ul data-bind="foreach: errors">
        <li data-bind="text: $data"></li>
     </ul>
   </div>
</div>

// see http://knockoutjs.com/documentation/observableArrays.html for info on removeAll
var vm = { errors: ko.observableArray([]) }


var r = {"Message":"The request is invalid.","ModelState":{"data.test":["The test field is required."]}};

vm.errors.removeAll();

for(p in r.ModelState) { 
  if (r.ModelState.hasOwnProperty(p)) { 
    vm.errors.push({prop: p, errors: r.ModelState[p]}); 
  }
}

ko.applyBindings(vm);

.errors {
  border: solid red 1px;
  border-radius: 10px 2px 2px;
  background-color: #FF8;
  color: #D10;
  padding: 10px;
  font-family: 'Segoe UI', 'Arial';
  }

<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>

<div class="errors" data-bind="foreach: errors">
   <div>
     <b>Errors for <!-- ko text: prop --><!-- /ko -->:</b>
     <ul data-bind="foreach: errors">
        <li data-bind="text: $data"></li>
     </ul>
   </div>
</div>

这篇关于通过jQuery Ajax在Web Api中显示无效的ModelState的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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