displaying invalid ModelState in Web Api via jquery ajax

410
November 23, 2016, at 8:33 PM

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

Answer 1

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>

Rent Charter Buses Company
READ ALSO
How to get a specific portion of the url using javascript?

How to get a specific portion of the url using javascript?

the above line gives me the url of my current page correctly and my url is:.

355
jQuery .Click on &lt;a&gt; not getting triggered on a mobile device

jQuery .Click on <a> not getting triggered on a mobile device

I have a dropdown menu for changing the language. In order to do that I need to react to the OnClick event and trigger my own code, so I have the following jQuery :.

343
Content loaded with ajax not triggering jQuery script

Content loaded with ajax not triggering jQuery script

I have the following draggable and selectable jQuery codes for item dragging/ selecting them all, the script works fine until the page is changed and the content inside <div id="content"></div> is loaded via ajax, then the draggable and selectable...

386
jQuery owlCarousel drag and drop Firefox issue

jQuery owlCarousel drag and drop Firefox issue

I have used owlCarousel 2 to display images and have tinymce 4 as WYSIWIG editor. .

571