I'm using MVC4 and knockout. I have a form on a page that is strongly typed to a viewmodel. In that viewmodel I have some validation defined, for instance:
[Required(ErrorMessage = "Title is required")]
public string Title { get; set; }
If I do a standard post to the form without the required field filled, my action sees that the model is not valid and returns to the view, and a main validation message is displayed because I have @Html.ValidationSummary
in my form. The individual field is also marked as invalid (with a message) because I have @Html.ValidationMessageFor
associated with the field
So then I added knockout and instead of just posting the form I now call ko.utils.postJson($("form")[0], self);
. Now most everything works, if I post the form with the required field not populated, my action detects that the model is invalid and returns to the view, except now the individual validation messages don't show up.
The filled in fields before the post are also lost. I tried to remedy this by reading in the mvc viewmodel and setting the variables to those values like so.
var model = @Html.Raw(Json.Encode(Model));
And then in my knockout viewmodel setting that value
self.Title = ko.observable(model.Title);
But then when I entered '1', it would fill in the field with '"1"' when the failed post returned.
This is not too complex of a form, so I do not want to introduce some new validation layer if it can be avoided. I don't mind there being a post for the validation.
Thanks, Dan