0
votes

I'm new in knockout. I want to use it in my project on ASP.NET MVC. But I don't understand how to show validation errors from server.

For example we have a authentication form with login and password inputs. Required or length validation I can make on client side. But what shall I do when I submit form to server but the user with submited login not found or password incorrect? How can I show server validation error with knockout.js?

Update 1

Controller code for example, it will return dictionary: item key, error message

[HttpPost]
public ActionResult MyAction(MyModel model)
{
    if(ModelState.IsValid)
    {
      ...
    }
    var errorList = ModelState.ToDictionary(
    kvp => kvp.Key,
    kvp => kvp.Value.Errors.Select(e => e.ErrorMessage).ToArray());
    return Json(errorList);
}
1
This will vary depends on the way you return the error. Will it be an exception, or you return the string with the error message, or else. Can you share the action controller code?muhihsan
@M. Ihsan, added in update to post.Oleg Volkov

1 Answers

0
votes

Add a propery that will represent an error message to your viewmodel and make it observable. Then do your ajax request to authenticate the user and when it's done you should get the result in JSON format, that you put inside that observable. Also you can add another property to indicate whether the request was successful or not and use it to make your error message visible.

The model could look like this:

var model = {
   ... // your current properties
   errorMsg : ko.observable(""),
   isError: ko.observable(false)
}

Use visible binding with isError to display error message when needed.

Sample

In the following example you get errors object along with the AJAX results and pass it to the setErrors method. Each member of the errors corresponds with the form field. The error message is only visible when the property is defined.

var model = {
  errors: {
    user: ko.observable(),
    email: ko.observable()
  },
  setErrors: function(errors) {
    this.errors.user(errors.user);
    this.errors.email(errors.email);
  }
};

ko.applyBindings(model);

// Get the results from AJAX and pass them as params:
var ajaxResults = {
  errors: {
    user: "Username is not available",
    email: "Incorrect email address"
  }
};

model.setErrors(ajaxResults.errors);
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>

<form>
    <input type="text" name="user">
    <span data-bind="visible: errors.user, text: errors.user"></span>
    <br>
    <input type="text" name="email">
    <span data-bind="visible: errors.email, text: errors.email"></span>
</form>