ASP.NET MVC razor form with knockout won't validate - asp.net-mvc

I have model like this (simplified)
public class User
{
[Required]
public string UserName { get; set; }
// Other fields
}
An MVC razor view with knockout viewModel that looks like this:
#using (Html.BeginForm("MyAction", FormMethod.Post, new { id = "profileEditorForm" }))
{
#Html.ValidationSummary(false)
#Html.LabelFor(n => n.UserName)
#Html.TextBoxFor(n => n.UserName, new { data_bind = "value: UserName" })
#Html.ValidationMessageFor(n => n.UserName)
#* Other fields *#
<p>
<input type="submit" value="Save" alt="" title="" />
Cancel
</p>
}
<script type="text/javascript">
$(function() {
var vm = new viewModel(#(Html.Raw(Json.Encode(#Model))));
ko.applyBindings(vm);
$("#profileEditorForm").validate({
submitHandler: function(form) {
alert('Validating ' + ko.toJSON(vm));
if (vm.save)
window.location.href = "/";
return false;
}
});
});
var viewModel = function(model) {
var self = this;
self.UserName = ko.observable(model.UserName);
// Other fields
self.save = function() {
alert('Saving ' + ko.toJSON(self));
}
};
};
</script>
I cannot get it to give me client side validation even though it goes through validate function (the alert insertion indicates that) and then straight into save and to posts back to MVC action something that is not valid.
Can you please help me how to enable client side validation (it is enabled in web.confir) on this form. Is it Knockout that ruins the day (although all the bindings are working perfectly fine? Or is it something I am looking at and don't see?
Help highly appreciated!

Validation doesn't work with knockout bindings....
You have to duplicate the validation in client side. The faster way is using knockout validation plugin, but it is slow when you have a lot of data..
https://github.com/ericmbarnard/Knockout-Validation
Or you can just use jquery validation.

Model Validation Will not work in knockout binding you have to download knockoutValidation.js file and use knockout validations
Example :
Validating UserName in KnockoutJS
var self = this;
self.UserName = ko.observable(UserName).extend({
required: {
message:"Please enter User Name"
}
});

Related

How to get jquery validation status with knockout custom binding?

I try to create view model that has no view information, such as calling jquery validation directly from view model before saving / sending the data to server.
var vm = function () {
var self = this;
self.password = ko.observable();
self.save = function (form) {
// I want to prevent any view information call directly from view model.
if ($(form).isValid()) {
// $.ajax({});
}
};
};
ko.applyBindings(new vm());
#using (Html.BeginForm(null, null, FormMethod.Post, new { data_bind = "submit: save" }))
Also I don't want to recreate knockout validation manually in the view model, because they have been generated by asp.mvc data annotation as jquery validation attributes.
[Required]
[StringLength(100, ErrorMessageResourceName = "ErrorMinStringLength", ErrorMessageResourceType = typeof(Locale), MinimumLength = 6)]
[DataType(DataType.Password)]
public string Password { get; set; }
#Html.PasswordFor(m => m.Password, new { data_bind = "value: Password" })
// Generated html in the browser view source.
<input type="password" name="Password" id="Password" data-val-required="The Password field is required." data-val-length-min="6" data-val-length-max="100" data-val-length="The Password must be at least 6 characters long." data-val="true" data-bind="value: Password">
I have created a simple custom binding that will update the the valid status as follow.
ko.bindingHandlers.jQueryIsValid = {
init: function (element, valueAccessor) {
$(element).closest("form").change(function () {
var observable = valueAccessor();
var isValid = $(element).valid();
observable(isValid);
});
}
};
And then update the html and view model as follow.
#using (Html.BeginForm(null, null, FormMethod.Post, new { data_bind = "submit: save, jQueryIsValid: isValid" }))
var vm = function () {
var self = this;
self.password = ko.observable();
self.isValid = ko.observable();
self.save = function () {
if (self.isValid()) {
// $.ajax({});
}
};
};
ko.applyBindings(new vm());
My point is to enforce mvvm pattern where as viewmodel should ideally have no knowledge about the view (like $(form).dosomething). I just not sure that above solution is the best way to do it. I might miss something about custom binding or existing knockout feature since I'm new to knockout.
Could anybody show the right / best way to do it?
The custom binding is unnecessary. The view-model doesn't need to be aware of the forms validity. The point being that save should only ever be called on a valid form. Also since you intend to replace the submit behaviour with an AJAX call you will need to ensure that upon clicking a submit button the form is not posted back.
You can achieve this as follows...
$('form').submit(function(e){
if ($(this).valid()) {
viewModel.save();
e.preventDefault();
}
});

Kockoutjs mapping plugin don't make entity model oservable [duplicate]

Bounty
It's been awhile and I still have a couple outstanding questions. I hope by adding a bounty maybe these questions will get answered.
How do you use html helpers with knockout.js
Why was document ready needed to make it work(see first edit for more information)
How do I do something like this if I am using the knockout mapping with my view models? As I do not have a function due to the mapping.
function AppViewModel() {
// ... leave firstName, lastName, and fullName unchanged here ...
this.capitalizeLastName = function() {
var currentVal = this.lastName(); // Read the current value
this.lastName(currentVal.toUpperCase()); // Write back a modified value
};
I want to use plugins for instance I want to be able to rollback observables as if a user cancels a request I want to be able to go back to the last value. From my research this seems to be achieved by people making plugins like editables
How do I use something like that if I am using mapping? I really don’t want to go to a method where I have in my view manual mapping were I map each MVC viewMode field to a KO model field as I want as little inline javascript as possible and that just seems like double the work and that’s why I like that mapping.
I am concerned that to make this work easy (by using mapping) I will lose a lot of KO power but on the other hand I am concerned that manual mapping will just be a lot of work and will make my views contain too much information and might become in the future harder to maintain(say if I remove a property in the MVC model I have to move it also in the KO viewmodel)
Original Post
I am using asp.net mvc 3 and I looking into knockout as it looks pretty cool but I am having a hard time figuring out how it works with asp.net mvc especially view models.
For me right now I do something like this
public class CourseVM
{
public int CourseId { get; set; }
[Required(ErrorMessage = "Course name is required")]
[StringLength(40, ErrorMessage = "Course name cannot be this long.")]
public string CourseName{ get; set; }
public List<StudentVm> StudentViewModels { get; set; }
}
I would have a Vm that has some basic properties like CourseName and it will have some simple validation on top of it. The Vm model might contain other view models in it as well if needed.
I would then pass this Vm to the View were I would use html helpers to help me display it to the user.
#Html.TextBoxFor(x => x.CourseName)
I might have some foreach loops or something to get the data out of the collection of Student View Models.
Then when I would submit the form I would use jquery and serialize array and send it to a controller action method that would bind it back to the viewmodel.
With knockout.js it is all different as you now got viewmodels for it and from all the examples I seen they don't use html helpers.
How do you use these 2 features of MVC with knockout.js?
I found this video and it briefly(last few minutes of the video # 18:48) goes into a way to use viewmodels by basically having an inline script that has the knockout.js viewmodel that gets assigned the values in the ViewModel.
Is this the only way to do it? How about in my example with having a collection of viewmodels in it? Do I have to have a foreach loop or something to extract all the values out and assign it into knockout?
As for html helpers the video says nothing about them.
These are the 2 areas that confuses the heck out of me as not many people seem to talk about it and it leaves me confused of how the initial values and everything is getting to the view when ever example is just some hard-coded value example.
Edit
I am trying what Darin Dimitrov has suggested and this seems to work(I had to make some changes to his code though). Not sure why I had to use document ready but somehow everything was not ready without it.
#model MvcApplication1.Models.Test
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<title>Index</title>
<script src="../../Scripts/jquery-1.5.1.js" type="text/javascript"></script>
<script src="../../Scripts/knockout-2.1.0.js" type="text/javascript"></script>
<script src="../../Scripts/knockout.mapping-latest.js" type="text/javascript"></script>
<script type="text/javascript">
$(function()
{
var model = #Html.Raw(Json.Encode(Model));
// Activates knockout.js
ko.applyBindings(model);
});
</script>
</head>
<body>
<div>
<p>First name: <strong data-bind="text: FirstName"></strong></p>
<p>Last name: <strong data-bind="text: LastName"></strong></p>
#Model.FirstName , #Model.LastName
</div>
</body>
</html>
I had to wrap it around a jquery document ready to make it work.
I also get this warning. Not sure what it is all about.
Warning 1 Conditional compilation is turned off -> #Html.Raw
So I have a starting point I guess at least will update when I done some more playing around and how this works.
I am trying to go through the interactive tutorials but use the a ViewModel instead.
Not sure how to tackle these parts yet
function AppViewModel() {
this.firstName = ko.observable("Bert");
this.lastName = ko.observable("Bertington");
}
or
function AppViewModel() {
// ... leave firstName, lastName, and fullName unchanged here ...
this.capitalizeLastName = function() {
var currentVal = this.lastName(); // Read the current value
this.lastName(currentVal.toUpperCase()); // Write back a modified value
};
Edit 2
I been able to figure out the first problem. No clue about the second problem. Yet though. Anyone got any ideas?
#model MvcApplication1.Models.Test
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<title>Index</title>
<script src="../../Scripts/jquery-1.5.1.js" type="text/javascript"></script>
<script src="../../Scripts/knockout-2.1.0.js" type="text/javascript"></script>
<script src="../../Scripts/knockout.mapping-latest.js" type="text/javascript"></script>
<script type="text/javascript">
$(function()
{
var model = #Html.Raw(Json.Encode(Model));
var viewModel = ko.mapping.fromJS(model);
ko.applyBindings(viewModel);
});
</script>
</head>
<body>
<div>
#*grab values from the view model directly*#
<p>First name: <strong data-bind="text: FirstName"></strong></p>
<p>Last name: <strong data-bind="text: LastName"></strong></p>
#*grab values from my second view model that I made*#
<p>SomeOtherValue <strong data-bind="text: Test2.SomeOtherValue"></strong></p>
<p>Another <strong data-bind="text: Test2.Another"></strong></p>
#*allow changes to all the values that should be then sync the above values.*#
<p>First name: <input data-bind="value: FirstName" /></p>
<p>Last name: <input data-bind="value: LastName" /></p>
<p>SomeOtherValue <input data-bind="value: Test2.SomeOtherValue" /></p>
<p>Another <input data-bind="value: Test2.Another" /></p>
#* seeing if I can do it with p tags and see if they all update.*#
<p data-bind="foreach: Test3">
<strong data-bind="text: Test3Value"></strong>
</p>
#*took my 3rd view model that is in a collection and output all values as a textbox*#
<table>
<thead><tr>
<th>Test3</th>
</tr></thead>
<tbody data-bind="foreach: Test3">
<tr>
<td>
<strong data-bind="text: Test3Value"></strong>
<input type="text" data-bind="value: Test3Value"/>
</td>
</tr>
</tbody>
</table>
Controller
public ActionResult Index()
{
Test2 test2 = new Test2
{
Another = "test",
SomeOtherValue = "test2"
};
Test vm = new Test
{
FirstName = "Bob",
LastName = "N/A",
Test2 = test2,
};
for (int i = 0; i < 10; i++)
{
Test3 test3 = new Test3
{
Test3Value = i.ToString()
};
vm.Test3.Add(test3);
}
return View(vm);
}
I think I have summarized all your questions, if I missed something please let me know (If you could summarize up all your questions in one place would be nice =))
Note. Compatibility with the ko.editable plug-in added
Download the full code
How do you use html helpers with knockout.js
This is easy:
#Html.TextBoxFor(model => model.CourseId, new { data_bind = "value: CourseId" })
Where:
value: CourseId indicates that you are binding the value property of the input control with the CourseId property from your model and your script model
The result is:
<input data-bind="value: CourseId" data-val="true" data-val-number="The field CourseId must be a number." data-val-required="The CourseId field is required." id="CourseId" name="CourseId" type="text" value="12" />
Why was document ready needed to make it work(see first edit for more information)
I do not understand yet why you need to use the ready event to serialize the model, but it seems that it is simply required (Not to worry about it though)
How do I do something like this if I am using the knockout mapping with my view models? As I do not have a function due to the mapping.
If I understand correctly you need to append a new method to the KO model, well that's easy merging models
For more info, in the section -Mapping from different sources-
function viewModel() {
this.addStudent = function () {
alert("de");
};
};
$(function () {
var jsonModel = '#Html.Raw(JsonConvert.SerializeObject(this.Model))';
var mvcModel = ko.mapping.fromJSON(jsonModel);
var myViewModel = new viewModel();
var g = ko.mapping.fromJS(myViewModel, mvcModel);
ko.applyBindings(g);
});
About the warning you were receiveing
Warning 1 Conditional compilation is turned off -> #Html.Raw
You need to use quotes
Compatibility with the ko.editable plug-in
I thought it was going to be more complex, but it turns out that the integration is really easy, in order to make your model editable just add the following line: (remember that in this case I am using a mixed model, from server and adding extension in client and the editable simply works... it's great):
ko.editable(g);
ko.applyBindings(g);
From here you just need to play with your bindings using the extensions added by the plug-in, for example, I have a button to start editing my fields like this and in this button I start the edit process:
this.editMode = function () {
this.isInEditMode(!this.isInEditMode());
this.beginEdit();
};
Then I have commit and cancel buttons with the following code:
this.executeCommit = function () {
this.commit();
this.isInEditMode(false);
};
this.executeRollback = function () {
if (this.hasChanges()) {
if (confirm("Are you sure you want to discard the changes?")) {
this.rollback();
this.isInEditMode(false);
}
}
else {
this.rollback();
this.isInEditMode(false);
}
};
And finally, I have one field to indicate whether the fields are in edit mode or not, this is just to bind the enable property.
this.isInEditMode = ko.observable(false);
About your array question
I might have some foreach loops or something to get the data out of the collection of Student View Models.
Then when I would submit the form I would use jquery and serialize array and send it to a controller action method that would bind it back to the viewmodel.
You can do the same with KO, in the following example, I will create the following output:
Basically here, you have two lists, created using Helpers and binded with KO, they have a dblClick event binded that when fired, remove the selected item from the current list and add it to the other list, when you post to the Controller, the content of each list is sent as JSON data and re-attached to the server model
Nuggets:
Newtonsoft
jQuery
knockoutjs
Knockout.Mapping
External scripts.
Controller code
[HttpGet]
public ActionResult Index()
{
var m = new CourseVM { CourseId = 12, CourseName = ".Net" };
m.StudentViewModels.Add(new StudentVm { ID = 545, Name = "Name from server", Lastname = "last name from server" });
return View(m);
}
[HttpPost]
public ActionResult Index(CourseVM model)
{
if (!string.IsNullOrWhiteSpace(model.StudentsSerialized))
{
model.StudentViewModels = JsonConvert.DeserializeObject<List<StudentVm>>(model.StudentsSerialized);
model.StudentsSerialized = string.Empty;
}
if (!string.IsNullOrWhiteSpace(model.SelectedStudentsSerialized))
{
model.SelectedStudents = JsonConvert.DeserializeObject<List<StudentVm>>(model.SelectedStudentsSerialized);
model.SelectedStudentsSerialized = string.Empty;
}
return View(model);
}
Model
public class CourseVM
{
public CourseVM()
{
this.StudentViewModels = new List<StudentVm>();
this.SelectedStudents = new List<StudentVm>();
}
public int CourseId { get; set; }
[Required(ErrorMessage = "Course name is required")]
[StringLength(100, ErrorMessage = "Course name cannot be this long.")]
public string CourseName { get; set; }
public List<StudentVm> StudentViewModels { get; set; }
public List<StudentVm> SelectedStudents { get; set; }
public string StudentsSerialized { get; set; }
public string SelectedStudentsSerialized { get; set; }
}
public class StudentVm
{
public int ID { get; set; }
public string Name { get; set; }
public string Lastname { get; set; }
}
CSHTML page
#using (Html.BeginForm())
{
#Html.ValidationSummary(true)
<fieldset>
<legend>CourseVM</legend>
<div>
<div class="editor-label">
#Html.LabelFor(model => model.CourseId)
</div>
<div class="editor-field">
#Html.TextBoxFor(model => model.CourseId, new { data_bind = "enable: isInEditMode, value: CourseId" })
#Html.ValidationMessageFor(model => model.CourseId)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.CourseName)
</div>
<div class="editor-field">
#Html.TextBoxFor(model => model.CourseName, new { data_bind = "enable: isInEditMode, value: CourseName" })
#Html.ValidationMessageFor(model => model.CourseName)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.StudentViewModels);
</div>
<div class="editor-field">
#Html.ListBoxFor(
model => model.StudentViewModels,
new SelectList(this.Model.StudentViewModels, "ID", "Name"),
new
{
style = "width: 37%;",
data_bind = "enable: isInEditMode, options: StudentViewModels, optionsText: 'Name', value: leftStudentSelected, event: { dblclick: moveFromLeftToRight }"
}
)
#Html.ListBoxFor(
model => model.SelectedStudents,
new SelectList(this.Model.SelectedStudents, "ID", "Name"),
new
{
style = "width: 37%;",
data_bind = "enable: isInEditMode, options: SelectedStudents, optionsText: 'Name', value: rightStudentSelected, event: { dblclick: moveFromRightToLeft }"
}
)
</div>
#Html.HiddenFor(model => model.CourseId, new { data_bind="value: CourseId" })
#Html.HiddenFor(model => model.CourseName, new { data_bind="value: CourseName" })
#Html.HiddenFor(model => model.StudentsSerialized, new { data_bind = "value: StudentsSerialized" })
#Html.HiddenFor(model => model.SelectedStudentsSerialized, new { data_bind = "value: SelectedStudentsSerialized" })
</div>
<p>
<input type="submit" value="Save" data-bind="enable: !isInEditMode()" />
<button data-bind="enable: !isInEditMode(), click: editMode">Edit mode</button><br />
<div>
<button data-bind="enable: isInEditMode, click: addStudent">Add Student</button>
<button data-bind="enable: hasChanges, click: executeCommit">Commit</button>
<button data-bind="enable: isInEditMode, click: executeRollback">Cancel</button>
</div>
</p>
</fieldset>
}
Scripts
<script src="#Url.Content("~/Scripts/jquery-1.7.2.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/knockout-2.1.0.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/knockout.mapping-latest.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/ko.editables.js")" type="text/javascript"></script>
<script type="text/javascript">
var g = null;
function ViewModel() {
this.addStudent = function () {
this.StudentViewModels.push(new Student(25, "my name" + new Date(), "my last name"));
this.serializeLists();
};
this.serializeLists = function () {
this.StudentsSerialized(ko.toJSON(this.StudentViewModels));
this.SelectedStudentsSerialized(ko.toJSON(this.SelectedStudents));
};
this.leftStudentSelected = ko.observable();
this.rightStudentSelected = ko.observable();
this.moveFromLeftToRight = function () {
this.SelectedStudents.push(this.leftStudentSelected());
this.StudentViewModels.remove(this.leftStudentSelected());
this.serializeLists();
};
this.moveFromRightToLeft = function () {
this.StudentViewModels.push(this.rightStudentSelected());
this.SelectedStudents.remove(this.rightStudentSelected());
this.serializeLists();
};
this.isInEditMode = ko.observable(false);
this.executeCommit = function () {
this.commit();
this.isInEditMode(false);
};
this.executeRollback = function () {
if (this.hasChanges()) {
if (confirm("Are you sure you want to discard the changes?")) {
this.rollback();
this.isInEditMode(false);
}
}
else {
this.rollback();
this.isInEditMode(false);
}
};
this.editMode = function () {
this.isInEditMode(!this.isInEditMode());
this.beginEdit();
};
}
function Student(id, name, lastName) {
this.ID = id;
this.Name = name;
this.LastName = lastName;
}
$(function () {
var jsonModel = '#Html.Raw(JsonConvert.SerializeObject(this.Model))';
var mvcModel = ko.mapping.fromJSON(jsonModel);
var myViewModel = new ViewModel();
g = ko.mapping.fromJS(myViewModel, mvcModel);
g.StudentsSerialized(ko.toJSON(g.StudentViewModels));
g.SelectedStudentsSerialized(ko.toJSON(g.SelectedStudents));
ko.editable(g);
ko.applyBindings(g);
});
</script>
Note: I just added these lines:
#Html.HiddenFor(model => model.CourseId, new { data_bind="value: CourseId" })
#Html.HiddenFor(model => model.CourseName, new { data_bind="value: CourseName" })
Because when I submit the form my fields are disabled, so the values were not transmitted to the server, that's why I added a couple of hidden fields to do the trick
You could serialize your ASP.NET MVC view model into a javascript variable:
#model CourseVM
<script type="text/javascript">
var model = #Html.Raw(Json.Encode(Model));
// go ahead and use the model javascript variable to bind with ko
</script>
There are lots of examples in the knockout documentation that you could go through.
To achieve the additional computed properties after server mapping you will need to further enhance your viewmodels on the client side.
For example:
var viewModel = ko.mapping.fromJS(model);
viewModel.capitalizedName = ko.computed(function() {...}, viewModel);
So everytime you map from raw JSON you would need to reapply the computed properties.
Additionally the mapping plugin provides the ability to incrementally update a viewmodel as opposed to recreating it every time you go back and forth (use an additional parameter in fromJS):
// Every time data is received from the server:
ko.mapping.fromJS(data, viewModel);
And that executes an incremental data update on your model of just properties that are mapped. You can read more about that in the mapping documentation
You mentioned in the comments on Darin's answer the FluentJSON package. I'm the author of that, but its use case is more specific than ko.mapping. I would generally only use it if your viewmodels are one way (ie. server -> client) and then data is posted back in some different format (or not at all). Or if your javascript viewmodel needs to be in a substantially different format from your server model.

How to use knockout.js with ASP.NET MVC ViewModels?

Bounty
It's been awhile and I still have a couple outstanding questions. I hope by adding a bounty maybe these questions will get answered.
How do you use html helpers with knockout.js
Why was document ready needed to make it work(see first edit for more information)
How do I do something like this if I am using the knockout mapping with my view models? As I do not have a function due to the mapping.
function AppViewModel() {
// ... leave firstName, lastName, and fullName unchanged here ...
this.capitalizeLastName = function() {
var currentVal = this.lastName(); // Read the current value
this.lastName(currentVal.toUpperCase()); // Write back a modified value
};
I want to use plugins for instance I want to be able to rollback observables as if a user cancels a request I want to be able to go back to the last value. From my research this seems to be achieved by people making plugins like editables
How do I use something like that if I am using mapping? I really don’t want to go to a method where I have in my view manual mapping were I map each MVC viewMode field to a KO model field as I want as little inline javascript as possible and that just seems like double the work and that’s why I like that mapping.
I am concerned that to make this work easy (by using mapping) I will lose a lot of KO power but on the other hand I am concerned that manual mapping will just be a lot of work and will make my views contain too much information and might become in the future harder to maintain(say if I remove a property in the MVC model I have to move it also in the KO viewmodel)
Original Post
I am using asp.net mvc 3 and I looking into knockout as it looks pretty cool but I am having a hard time figuring out how it works with asp.net mvc especially view models.
For me right now I do something like this
public class CourseVM
{
public int CourseId { get; set; }
[Required(ErrorMessage = "Course name is required")]
[StringLength(40, ErrorMessage = "Course name cannot be this long.")]
public string CourseName{ get; set; }
public List<StudentVm> StudentViewModels { get; set; }
}
I would have a Vm that has some basic properties like CourseName and it will have some simple validation on top of it. The Vm model might contain other view models in it as well if needed.
I would then pass this Vm to the View were I would use html helpers to help me display it to the user.
#Html.TextBoxFor(x => x.CourseName)
I might have some foreach loops or something to get the data out of the collection of Student View Models.
Then when I would submit the form I would use jquery and serialize array and send it to a controller action method that would bind it back to the viewmodel.
With knockout.js it is all different as you now got viewmodels for it and from all the examples I seen they don't use html helpers.
How do you use these 2 features of MVC with knockout.js?
I found this video and it briefly(last few minutes of the video # 18:48) goes into a way to use viewmodels by basically having an inline script that has the knockout.js viewmodel that gets assigned the values in the ViewModel.
Is this the only way to do it? How about in my example with having a collection of viewmodels in it? Do I have to have a foreach loop or something to extract all the values out and assign it into knockout?
As for html helpers the video says nothing about them.
These are the 2 areas that confuses the heck out of me as not many people seem to talk about it and it leaves me confused of how the initial values and everything is getting to the view when ever example is just some hard-coded value example.
Edit
I am trying what Darin Dimitrov has suggested and this seems to work(I had to make some changes to his code though). Not sure why I had to use document ready but somehow everything was not ready without it.
#model MvcApplication1.Models.Test
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<title>Index</title>
<script src="../../Scripts/jquery-1.5.1.js" type="text/javascript"></script>
<script src="../../Scripts/knockout-2.1.0.js" type="text/javascript"></script>
<script src="../../Scripts/knockout.mapping-latest.js" type="text/javascript"></script>
<script type="text/javascript">
$(function()
{
var model = #Html.Raw(Json.Encode(Model));
// Activates knockout.js
ko.applyBindings(model);
});
</script>
</head>
<body>
<div>
<p>First name: <strong data-bind="text: FirstName"></strong></p>
<p>Last name: <strong data-bind="text: LastName"></strong></p>
#Model.FirstName , #Model.LastName
</div>
</body>
</html>
I had to wrap it around a jquery document ready to make it work.
I also get this warning. Not sure what it is all about.
Warning 1 Conditional compilation is turned off -> #Html.Raw
So I have a starting point I guess at least will update when I done some more playing around and how this works.
I am trying to go through the interactive tutorials but use the a ViewModel instead.
Not sure how to tackle these parts yet
function AppViewModel() {
this.firstName = ko.observable("Bert");
this.lastName = ko.observable("Bertington");
}
or
function AppViewModel() {
// ... leave firstName, lastName, and fullName unchanged here ...
this.capitalizeLastName = function() {
var currentVal = this.lastName(); // Read the current value
this.lastName(currentVal.toUpperCase()); // Write back a modified value
};
Edit 2
I been able to figure out the first problem. No clue about the second problem. Yet though. Anyone got any ideas?
#model MvcApplication1.Models.Test
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<title>Index</title>
<script src="../../Scripts/jquery-1.5.1.js" type="text/javascript"></script>
<script src="../../Scripts/knockout-2.1.0.js" type="text/javascript"></script>
<script src="../../Scripts/knockout.mapping-latest.js" type="text/javascript"></script>
<script type="text/javascript">
$(function()
{
var model = #Html.Raw(Json.Encode(Model));
var viewModel = ko.mapping.fromJS(model);
ko.applyBindings(viewModel);
});
</script>
</head>
<body>
<div>
#*grab values from the view model directly*#
<p>First name: <strong data-bind="text: FirstName"></strong></p>
<p>Last name: <strong data-bind="text: LastName"></strong></p>
#*grab values from my second view model that I made*#
<p>SomeOtherValue <strong data-bind="text: Test2.SomeOtherValue"></strong></p>
<p>Another <strong data-bind="text: Test2.Another"></strong></p>
#*allow changes to all the values that should be then sync the above values.*#
<p>First name: <input data-bind="value: FirstName" /></p>
<p>Last name: <input data-bind="value: LastName" /></p>
<p>SomeOtherValue <input data-bind="value: Test2.SomeOtherValue" /></p>
<p>Another <input data-bind="value: Test2.Another" /></p>
#* seeing if I can do it with p tags and see if they all update.*#
<p data-bind="foreach: Test3">
<strong data-bind="text: Test3Value"></strong>
</p>
#*took my 3rd view model that is in a collection and output all values as a textbox*#
<table>
<thead><tr>
<th>Test3</th>
</tr></thead>
<tbody data-bind="foreach: Test3">
<tr>
<td>
<strong data-bind="text: Test3Value"></strong>
<input type="text" data-bind="value: Test3Value"/>
</td>
</tr>
</tbody>
</table>
Controller
public ActionResult Index()
{
Test2 test2 = new Test2
{
Another = "test",
SomeOtherValue = "test2"
};
Test vm = new Test
{
FirstName = "Bob",
LastName = "N/A",
Test2 = test2,
};
for (int i = 0; i < 10; i++)
{
Test3 test3 = new Test3
{
Test3Value = i.ToString()
};
vm.Test3.Add(test3);
}
return View(vm);
}
I think I have summarized all your questions, if I missed something please let me know (If you could summarize up all your questions in one place would be nice =))
Note. Compatibility with the ko.editable plug-in added
Download the full code
How do you use html helpers with knockout.js
This is easy:
#Html.TextBoxFor(model => model.CourseId, new { data_bind = "value: CourseId" })
Where:
value: CourseId indicates that you are binding the value property of the input control with the CourseId property from your model and your script model
The result is:
<input data-bind="value: CourseId" data-val="true" data-val-number="The field CourseId must be a number." data-val-required="The CourseId field is required." id="CourseId" name="CourseId" type="text" value="12" />
Why was document ready needed to make it work(see first edit for more information)
I do not understand yet why you need to use the ready event to serialize the model, but it seems that it is simply required (Not to worry about it though)
How do I do something like this if I am using the knockout mapping with my view models? As I do not have a function due to the mapping.
If I understand correctly you need to append a new method to the KO model, well that's easy merging models
For more info, in the section -Mapping from different sources-
function viewModel() {
this.addStudent = function () {
alert("de");
};
};
$(function () {
var jsonModel = '#Html.Raw(JsonConvert.SerializeObject(this.Model))';
var mvcModel = ko.mapping.fromJSON(jsonModel);
var myViewModel = new viewModel();
var g = ko.mapping.fromJS(myViewModel, mvcModel);
ko.applyBindings(g);
});
About the warning you were receiveing
Warning 1 Conditional compilation is turned off -> #Html.Raw
You need to use quotes
Compatibility with the ko.editable plug-in
I thought it was going to be more complex, but it turns out that the integration is really easy, in order to make your model editable just add the following line: (remember that in this case I am using a mixed model, from server and adding extension in client and the editable simply works... it's great):
ko.editable(g);
ko.applyBindings(g);
From here you just need to play with your bindings using the extensions added by the plug-in, for example, I have a button to start editing my fields like this and in this button I start the edit process:
this.editMode = function () {
this.isInEditMode(!this.isInEditMode());
this.beginEdit();
};
Then I have commit and cancel buttons with the following code:
this.executeCommit = function () {
this.commit();
this.isInEditMode(false);
};
this.executeRollback = function () {
if (this.hasChanges()) {
if (confirm("Are you sure you want to discard the changes?")) {
this.rollback();
this.isInEditMode(false);
}
}
else {
this.rollback();
this.isInEditMode(false);
}
};
And finally, I have one field to indicate whether the fields are in edit mode or not, this is just to bind the enable property.
this.isInEditMode = ko.observable(false);
About your array question
I might have some foreach loops or something to get the data out of the collection of Student View Models.
Then when I would submit the form I would use jquery and serialize array and send it to a controller action method that would bind it back to the viewmodel.
You can do the same with KO, in the following example, I will create the following output:
Basically here, you have two lists, created using Helpers and binded with KO, they have a dblClick event binded that when fired, remove the selected item from the current list and add it to the other list, when you post to the Controller, the content of each list is sent as JSON data and re-attached to the server model
Nuggets:
Newtonsoft
jQuery
knockoutjs
Knockout.Mapping
External scripts.
Controller code
[HttpGet]
public ActionResult Index()
{
var m = new CourseVM { CourseId = 12, CourseName = ".Net" };
m.StudentViewModels.Add(new StudentVm { ID = 545, Name = "Name from server", Lastname = "last name from server" });
return View(m);
}
[HttpPost]
public ActionResult Index(CourseVM model)
{
if (!string.IsNullOrWhiteSpace(model.StudentsSerialized))
{
model.StudentViewModels = JsonConvert.DeserializeObject<List<StudentVm>>(model.StudentsSerialized);
model.StudentsSerialized = string.Empty;
}
if (!string.IsNullOrWhiteSpace(model.SelectedStudentsSerialized))
{
model.SelectedStudents = JsonConvert.DeserializeObject<List<StudentVm>>(model.SelectedStudentsSerialized);
model.SelectedStudentsSerialized = string.Empty;
}
return View(model);
}
Model
public class CourseVM
{
public CourseVM()
{
this.StudentViewModels = new List<StudentVm>();
this.SelectedStudents = new List<StudentVm>();
}
public int CourseId { get; set; }
[Required(ErrorMessage = "Course name is required")]
[StringLength(100, ErrorMessage = "Course name cannot be this long.")]
public string CourseName { get; set; }
public List<StudentVm> StudentViewModels { get; set; }
public List<StudentVm> SelectedStudents { get; set; }
public string StudentsSerialized { get; set; }
public string SelectedStudentsSerialized { get; set; }
}
public class StudentVm
{
public int ID { get; set; }
public string Name { get; set; }
public string Lastname { get; set; }
}
CSHTML page
#using (Html.BeginForm())
{
#Html.ValidationSummary(true)
<fieldset>
<legend>CourseVM</legend>
<div>
<div class="editor-label">
#Html.LabelFor(model => model.CourseId)
</div>
<div class="editor-field">
#Html.TextBoxFor(model => model.CourseId, new { data_bind = "enable: isInEditMode, value: CourseId" })
#Html.ValidationMessageFor(model => model.CourseId)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.CourseName)
</div>
<div class="editor-field">
#Html.TextBoxFor(model => model.CourseName, new { data_bind = "enable: isInEditMode, value: CourseName" })
#Html.ValidationMessageFor(model => model.CourseName)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.StudentViewModels);
</div>
<div class="editor-field">
#Html.ListBoxFor(
model => model.StudentViewModels,
new SelectList(this.Model.StudentViewModels, "ID", "Name"),
new
{
style = "width: 37%;",
data_bind = "enable: isInEditMode, options: StudentViewModels, optionsText: 'Name', value: leftStudentSelected, event: { dblclick: moveFromLeftToRight }"
}
)
#Html.ListBoxFor(
model => model.SelectedStudents,
new SelectList(this.Model.SelectedStudents, "ID", "Name"),
new
{
style = "width: 37%;",
data_bind = "enable: isInEditMode, options: SelectedStudents, optionsText: 'Name', value: rightStudentSelected, event: { dblclick: moveFromRightToLeft }"
}
)
</div>
#Html.HiddenFor(model => model.CourseId, new { data_bind="value: CourseId" })
#Html.HiddenFor(model => model.CourseName, new { data_bind="value: CourseName" })
#Html.HiddenFor(model => model.StudentsSerialized, new { data_bind = "value: StudentsSerialized" })
#Html.HiddenFor(model => model.SelectedStudentsSerialized, new { data_bind = "value: SelectedStudentsSerialized" })
</div>
<p>
<input type="submit" value="Save" data-bind="enable: !isInEditMode()" />
<button data-bind="enable: !isInEditMode(), click: editMode">Edit mode</button><br />
<div>
<button data-bind="enable: isInEditMode, click: addStudent">Add Student</button>
<button data-bind="enable: hasChanges, click: executeCommit">Commit</button>
<button data-bind="enable: isInEditMode, click: executeRollback">Cancel</button>
</div>
</p>
</fieldset>
}
Scripts
<script src="#Url.Content("~/Scripts/jquery-1.7.2.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/knockout-2.1.0.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/knockout.mapping-latest.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/ko.editables.js")" type="text/javascript"></script>
<script type="text/javascript">
var g = null;
function ViewModel() {
this.addStudent = function () {
this.StudentViewModels.push(new Student(25, "my name" + new Date(), "my last name"));
this.serializeLists();
};
this.serializeLists = function () {
this.StudentsSerialized(ko.toJSON(this.StudentViewModels));
this.SelectedStudentsSerialized(ko.toJSON(this.SelectedStudents));
};
this.leftStudentSelected = ko.observable();
this.rightStudentSelected = ko.observable();
this.moveFromLeftToRight = function () {
this.SelectedStudents.push(this.leftStudentSelected());
this.StudentViewModels.remove(this.leftStudentSelected());
this.serializeLists();
};
this.moveFromRightToLeft = function () {
this.StudentViewModels.push(this.rightStudentSelected());
this.SelectedStudents.remove(this.rightStudentSelected());
this.serializeLists();
};
this.isInEditMode = ko.observable(false);
this.executeCommit = function () {
this.commit();
this.isInEditMode(false);
};
this.executeRollback = function () {
if (this.hasChanges()) {
if (confirm("Are you sure you want to discard the changes?")) {
this.rollback();
this.isInEditMode(false);
}
}
else {
this.rollback();
this.isInEditMode(false);
}
};
this.editMode = function () {
this.isInEditMode(!this.isInEditMode());
this.beginEdit();
};
}
function Student(id, name, lastName) {
this.ID = id;
this.Name = name;
this.LastName = lastName;
}
$(function () {
var jsonModel = '#Html.Raw(JsonConvert.SerializeObject(this.Model))';
var mvcModel = ko.mapping.fromJSON(jsonModel);
var myViewModel = new ViewModel();
g = ko.mapping.fromJS(myViewModel, mvcModel);
g.StudentsSerialized(ko.toJSON(g.StudentViewModels));
g.SelectedStudentsSerialized(ko.toJSON(g.SelectedStudents));
ko.editable(g);
ko.applyBindings(g);
});
</script>
Note: I just added these lines:
#Html.HiddenFor(model => model.CourseId, new { data_bind="value: CourseId" })
#Html.HiddenFor(model => model.CourseName, new { data_bind="value: CourseName" })
Because when I submit the form my fields are disabled, so the values were not transmitted to the server, that's why I added a couple of hidden fields to do the trick
You could serialize your ASP.NET MVC view model into a javascript variable:
#model CourseVM
<script type="text/javascript">
var model = #Html.Raw(Json.Encode(Model));
// go ahead and use the model javascript variable to bind with ko
</script>
There are lots of examples in the knockout documentation that you could go through.
To achieve the additional computed properties after server mapping you will need to further enhance your viewmodels on the client side.
For example:
var viewModel = ko.mapping.fromJS(model);
viewModel.capitalizedName = ko.computed(function() {...}, viewModel);
So everytime you map from raw JSON you would need to reapply the computed properties.
Additionally the mapping plugin provides the ability to incrementally update a viewmodel as opposed to recreating it every time you go back and forth (use an additional parameter in fromJS):
// Every time data is received from the server:
ko.mapping.fromJS(data, viewModel);
And that executes an incremental data update on your model of just properties that are mapped. You can read more about that in the mapping documentation
You mentioned in the comments on Darin's answer the FluentJSON package. I'm the author of that, but its use case is more specific than ko.mapping. I would generally only use it if your viewmodels are one way (ie. server -> client) and then data is posted back in some different format (or not at all). Or if your javascript viewmodel needs to be in a substantially different format from your server model.

unobtrusive client validation in knockout template binding

I have a model with data annotations and i am an dynamically binding that with viewmodel using knockout template binding and mapping plugin. I am trying to do a unobtrusive client validation to be done on my model. How we can do that in this scenario. Any help/suggestions?
public class MyUser
{
[Required]
[StringLength(35)]
public string Username { get; set; }
[Required]
[StringLength(35)]
public string Forename { get; set; }
[Required]
[StringLength(35)]
public string Surname { get; set; }
}
In my view i am dynamically template binding a list of MyUser using ajax.
public JsonResult TestKnockout()
{
IList<MyUser> myUserList = new List<MyUser>();
myUserList.Add(new MyUser { Username = "ajohn", Surname = "surname" });
myUserList.Add(new MyUser { Username = "ajohn1", Surname = "surname1" });
return Json(myUserList, JsonRequestBehavior.AllowGet);
}
}
View:
<form id="Userform" action='#Url.Action("Save", "Home")' data-bind="template: {name: 'UserTemplate', foreach:UserList}">
<input type="Submit" name="name" value="Submit" />
</form>
<script id="UserTemplate" type="text/Html">
<input type="text" data-bind="value: Username"></input>
<input type="text" data-bind="value: Forename"></input>
<input type="text" data-bind="value: Surname"></input>
</script>
<script type="text/javascript">
var viewModel = {
UserList: ko.observableArray(new Array()),
Save: function () {
//// reached here means validation is done.
alert("Save");
}
}
ko.applyBindings(viewModel);
$.ajax({
type: 'GET',
url: '../Home/TestKnockout',
contentType: "application/json",
success: function (data) {
$.each(ko.mapping.fromJS(data)(), function () {
viewModel.UserList.push(this);
})
// attach the jquery unobtrusive validator
$.validator.unobtrusive.parse("#Userform");
// bind the submit handler to unobtrusive validation.
$("#Userform").data("validator").settings.submitHandler = viewModel.Save;
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
});
</script>
pilavdzice and drogon answers are quite good but we forget the basic point.
Since we are using an MVVM pattern for the seperation of UI and data (+vm) we don't want to perform UI validation but DATA VALIDATION. Those two are quite different, jquery validate is a great plugin but it does UI validation (it starts from UI to check the fields).
I have found knockout validation plugin which seems to do quite well and what it does is to go the opposite road, it validates your viewmodel and not your UI (it actually maps to UI elements to display the errors).
Unfortunately If your viewmodel gets complex, that plugin will have some problems, but in any case this is the way to go.
UI validation is perfect as long as we are not using an MVVM pattern, after all what do we separate the components (M-V-VM) for ?
Hope I helped !
Thanks!
I had the same problem as you so I wrote the following component.
https://www.nuget.org/packages/ScriptAnnotations/
https://scriptannotations.codeplex.com/
Please let me know if this helps.
I would go with jquery's event binding for this.
First, add your data-val attributes to the inputs you want to validate. (To figure out which data-val attributes to use, I usually bind a form server-side to a model and view source.)
<input data-val-required="test" data-val="true" data-bind="visible:
$parent.userEditMode, value: FirstName" />
Second, add a validation utility function --this calls the jquery validation plugin used by MVC under the covers.
function validateForm(thisForm) {
var val = thisForm.validate();
var isValid = val.form();
alert(isValid);
if (!isValid) {
thisForm.find('.input-validation-error').first().focus();
}
return isValid;
}
Third, call validate before issuing your viewmodel method. Make sure to remove the "click" data-bind attribute from the markup in your page.
$('#..your form id...').live('submit', function (e) {
e.preventDefault();
if(validateForm($(this)))
viewModel.saveUser();
});
If you are using knockoutjs and jquery, I came up with the following very simple method for doing basic validation.
Wherever you want to display the error message on your page, include a span tag like this:
<span name="validationError" style="color:Red"
data-bind="visible: yourValidationFunction(FieldNameToValidate())">
* Required.
</span>
Obviously you need to write "yourValidationFunction" to do whatever you want it to do. It just needs to return true or false, true means display the error.
You can use jquery to prevent a user from proceeding if any validations errors are displayed. You probably already have a save button that triggers a javascript function to do some ajax or whatever, so just include this at the top of it:
if ($("[name='validationError']:visible").length > 0) {
alert('Please correct all errors before continuing.');
return;
}
This is a lot simpler and more flexible than many other validation solutions out there. You can position your error message wherever you want, and you don't need to learn how to use some validation library.

Unobtrusive validation doesn't work with Ajax.BeginForm

I have View with Model1 where I put Ajax.BeginForm() and in this View i have PartialView with Model2 where i put Ajax.BeginForm(). So only in first form working unobtrusive validation. Why only in first form working validation?
first View
#model Model1
#using (Ajax.BeginForm("Action1","Controller",null,new AjaxOption(){ onSuccess = "alert('=)')"},null)
{
<intput type="submit" value="Save" />
}
Model2 model2 = new Model2();
#Html.EditorFor(m=>model2)
**In Model2 view i have. **
#model Model2
#using (Ajax.BeginForm("AddStreet","Controller",new AjaxOption(){onSuccess = "alert('=)'")},option,null)
{
#Html.LabelFor(m => Model.Name):
#Html.TextBoxFor(m => Model.Name)
#Html.ValidationMessageFor(m => Model.Name)
<intput type="submit" value="Save" />
}
Thanks #Darin Dimitrov for answer.
That's because the second view is loaded with AJAX at a later stage and you need to call $.validator.unobtrusive.parse(...)
immediately after its contents is injected into the DOM in order to enable unobtrusive validation. Look at the following blog post for more details.
So in your case, instead of alerting in the OnSuccess callback of the first AJAX call, subscribe to a javascript function which will invoke this method:
#using (Ajax.BeginForm(
"Action1",
"Controller",
null,
new AjaxOptions {
OnSuccess = "onSuccess",
UpdateTargetId = "result"
},
null)
)
{
<input type="submit" value="Save" />
}
and then in your javascript file:
var onSuccess = function(result) {
// enable unobtrusive validation for the contents
// that was injected into the <div id="result"></div> node
$.validator.unobtrusive.parse($(result));
};
You need to add those 2 files in you Partial View even if it is already in the Shared/_Layout.cshtml:
<script src="#Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.validate.unobtrusive.js")" type="text/javascript"></script>
Or place this in your Partial:
<script type="text/javascript" language=javascript>
$.validator.unobtrusive.parse(document);
</script>
This solution worked best for me.
$.validator.unobtrusive.parse(document);
The answer of Darin Dimitrov only works when validate() of the jquery validate plugin has not been called until the Ajax success handler is called. I can't think of a scenario where this could be the case, thus i wonder why the answer was accepted as correct.
Perhaps a change in the jquery validate code in the past now causes the following issue:
The issue is that validate() executes the following line first
// Check if a validator for this form was already created
var validator = $.data( this[ 0 ], "validator" );
if ( validator ) {
return validator;
which means that the validator object is returned when validate() is called without and further handling of the options passed.
This also means that a later call to $.validator.unobtrusive.parse(...) or $.validator.unobtrusive.parseElement(...) which executes a
$form.validate(this.options) <- this.options holds the new rules parsed from HTML
to update the options of the validator has no effect because the options are not processed at all.
The solution here is to update the validator manually like
var $htmlCode = $("your html");
$.validator.unobtrusive.parse($htmlCode, true); // true means no validate() call
// now get the validation info collected in parse()
var validationInfo = $form.data("unobtrusiveValidation");
var $validator = $form.validate(); // get validator and ...
$validator.settings.rules = validationInfo.options.rules; // ... update its rules
$validator.settings.messages = validationInfo.options.messages; // ... update its messages
Revalidating the form (e.g. clicking submit) should now result in the expected results.
Here is a full example witch also includes code from the already accepted answer:
Razor
#using (Ajax.BeginForm(
"Action1",
"Controller",
null,
new AjaxOptions {
OnSuccess = "onSuccess",
UpdateTargetId = "result"
},
null)
)
{
<input type="submit" value="Save" />
}
Javascript
var onSuccess = function(result) {
var $htmlCode = $(result);
$.validator.unobtrusive.parse($htmlCode, true); // true means no validate() call
// now get the validation info collected in parse()
var validationInfo = $form.data("unobtrusiveValidation");
var $validator = $form.validate(); // get validator and ...
$validator.settings.rules = validationInfo.options.rules; // ... update its rules
$validator.settings.messages = validationInfo.options.messages; // ... update its messages
};
--
As a side note, manually updating the validator is also possible by using the rules() method like
$yourHtmlField.rules( "add", {
required: true,
messages: {
required: "Required input"
}
});
as this directly updates the rules of the validator without the unobtrusive stuff. But then the data-val attributes are rendered useless.
You have to add a reference to jquery.unobtrusive-ajax.js to enable the validation within Ajax Form
Something like this:
<script type="text/javascript" src="/Scripts/jquery.unobtrusive-ajax.js"></script>

Resources