displaying invalid ModelState in Web Api via jquery ajax

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.

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)

ok here we go

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

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);

                    },
                });
            }

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).

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?)


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>
链接地址: http://www.djcxy.com/p/67992.html

上一篇: ModelState验证

下一篇: 通过jquery ajax在Web Api中显示无效的ModelState