I mainly had problems displaying modelstate errors returned by the controller (WebApi). Using MVC4, jQuery and knockout. Hope you see what I'm trying to achieve from below - thanks in advance.
View: -
<div class="editor-field"> @Html.TextBoxFor(model => model.CostCode, new { placeholder = "cost/budget code", data_bind = "value: CostCode" }) </div> <div> @Html.ValidationMessageFor(model => model.CostCode) </div>
knockout viewmodel makes a message / send: -
if (validator.valid()) { console.log('is valid'); $.ajax({ url: '/api/Booking/CompleteBooking', type: 'POST', dataType: 'json', data: ko.mapping.toJS(self), error: function (jqXHR) { extractErrors(jqXHR, validator); }, success: function (data) { console.log(data); } }); } function extractErrors(jqXhr, validator) { var data = $.parseJSON(jqXhr.responseText), errors = { }; $.each(data.ModelState, function (i, item) { errors[i] = item; }); console.log(errors); validator.showErrors(errors); }
Controller: -
[ModelValidationFilter] public HttpResponseMessage CompleteBooking(AdditionalBookingInfoViewModel model) { return new HttpResponseMessage(HttpStatusCode.OK); }
ActionFilterAttribute (note that the state of the model is sent back)
public class ModelValidationFilterAttribute : ActionFilterAttribute { public override void OnActionExecuting(HttpActionContext actionContext) { if (!actionContext.ModelState.IsValid) { actionContext.Response = actionContext.Request.CreateErrorResponse(HttpStatusCode.BadRequest, actionContext.ModelState); } } }
Markup provided: -

Firebug answer: -

Now I know that the validator will try to find an element named "model.CostCode" not just "CostCode" as it appears in the markup, but I tried to set the Id and name to "model.CostCode" 'to match, but it doesnโt have no value. I think there is a problem with my extractErrors function.
If I hard-coded an error message, then the validator is working fine
validator.showErrors({ "CostCode" : "Test test test!" });

By the way, is this an acceptable way to display scan messages on the server side or am I barking the wrong tree all the time? Any pointers / comments are very welcome.