I have a viewmodel bound on a html page for submitting a form.
When I submit the form, the viewmodel itself is coming up as empty but the observable items within the viewmodel are populated.
Hence I am unable to post the viewmodel to the server as it is coming up null.
Please help!
My html:
<p>First name:<input data-bind='value: firstName' /></p>
<p>Last name:<input data-bind='value: lastName' /></p>
<p><button data-bind='click: saveUserData'>Submit</button></p>
And my script:
function PersonViewModel() {
var self = this;
this.firstName = ko.observable();
this.lastName = ko.observable();
this.saveUserData = function () {
alert(ko.toJSON(self)); // alerts '{}' i.e. nothing
alert(ko.toJSON(self.firstName())); // alerts value of the firsTname
//do the post here
};
};
ko.applyBindings(new PersonViewModel());
I found the root for this issue and am posting the solution here so that it would be helpful to anyone if they stumble upon similar issue.
Solution: Perform the binding (applyBindings function call) after the document is ready. i.e.,
$(document).ready(function () {
ko.applyBindings(new PersonViewModel());
});
Thanks!
Related
Questions about ASP.NET MVC, Knockout.js and the mapping plugin abound. I have the following (very simple "getting started") example, which works. However, I would like feedback on whether this is the recommended approach. Primarily, I am interested in future models being significantly more complex (children, dropdowns, etc.). I feel maintaining two sets of models is not justifiable, thus my desire to use the mapping plugin.
PS: I wouldn't mind having the form submit, but I couldn't get that to work due to all different issues, apparently related to URL-encoding of string values with quotes by ko.utils.postJSON. Any updates on that would be appreciated also.
HTML
<h2>Simple View</h2>
<p>A simple model with 2 properties</p>
<p>Model property "Name": <span data-bind="text: Name"></span></p>
<p>Model property "Count" (just some integer): <span data-bind="text: Count"></span></p>
<form data-bind="submit: save">
<h3>Editing</h3>
<p>Name: <input type="text" data-bind="value: Name" /></p>
<p>Count: <input type="text" data-bind="value: Count" /></p>
<h3>Posting Back</h3>
<button type="submit">Update</button>
</form>
JavaScript
<script type="text/javascript">
var KoViewModel;
$(function () {
KoViewModel = ko.mapping.fromJSON('#Html.Raw(Newtonsoft.Json.JsonConvert.SerializeObject(Model))');
ko.applyBindings(KoViewModel);
});
var save = function () {
$.ajax({
url: location.href,
type: 'POST',
data: ko.mapping.toJSON(KoViewModel),
contentType: 'application/json; charset=utf-8',
success: function (data) {
ko.mapping.fromJSON(data, KoViewModel);
}
});
}
</script>
Server-Side
public ActionResult Index()
{
Models.SimpleModel m = new Models.SimpleModel();
m.Name = "Some name";
m.Count = 1;
return View(m);
}
[HttpPost]
public JsonResult Index(Models.SimpleModel fc)
{
fc.Name += " (updated)";
fc.Count++;
return (new JsonResult() { Data = Newtonsoft.Json.JsonConvert.SerializeObject(fc) });
}
Thanks for any insights!
I would structure the script differently.
function SimpleModel(data) {
var self = this;
// data
self.Name = ko.observable();
self.Count = ko.observable();
// api
self.load = function (data) {
if (data) ko.mapping.fromJSON(data, {}, self);
};
self.save = function () {
return $.ajax({
type: 'POST',
url: location.href,
data: ko.mapping.toJSON(self),
contentType: 'application/json; charset=utf-8',
}).done(self.load);
};
// init
self.load(data);
}
// later... -------------------------------------------------------------------------
$(function () {
var data = '#Html.Raw(Newtonsoft.Json.JsonConvert.SerializeObject(Model))';
ko.applyBindings( new SimpleModel(data) );
});
Advantages:
All data properties of the viewmodel are explicitly defined. This helps reduce bugs because it is immediately obvious what a viewmodel looks like. It also helps reduce run-time errors because properties will exist even if they happen to be missing on the JSON input. This way, the view can always bind without any problems.
You can move the viewmodel to a separate script file.
The viewmodel can initialize itself from the data you pass into the constructor. This will be useful if you refactor the application - for example when your viewmodel suddenly becomes a part of a larger viewmodel.
No awkward references to global variables or separate helper functions, the viewmodel is self-contained.
Returning the Ajax promise from the save method allows you to attach extra behavior without rewiring the viewmodel:
var vm = new SimpleModel(data);
// programmatically save the model
vm.save().done(function () {
// whatever
localStorage.setItem('lastAutoSave', Date.now());
});
here i got a sample code which said KnockoutJS Mapping plugin automatically bind UI.
here is code
<script src="~/Scripts/knockout.mapping-latest.js"></script>
<script type="text/javascript">
$(function() {
var viewModel = ko.mapping.fromJS(#Html.Raw(Model.ToJson()));
ko.applyBindings(viewModel);
});
</script>
suppose my html binding as follows
<p>First name: <strong data-bind="text: firstName"></strong></p>
<p>Last name: <strong data-bind="text: lastName"></strong></p>
and my server side model return json like
{fname:Josh;lname:Steve};
so here my question is how KnockoutJS Mapping plugin could understand that fname value need to map to databinding firstName & lname need to map to databinding lastName ?
am i clear what i am trying to say. so guide me in this case how one could bind json to html UI through KnockoutJS Mapping plugin.
in this situation KnockoutJS Mapping plugin would be right choice or not ?
do i need to bind manually by viewmode like
First name:
Last name:
json as follows var person = {fname:Josh;lname:Steve};
var viewModel = function(person) {
this.firstname= ko.observable(person.fname);
this.lastname= ko.observable(person.lname);
};
ko.applyBindings(new viewModel(person));
As requested in the comment I put this as a possible answer.
If you have model with many properties and want only some of them to map to different names, this is the way to do it:
var viewModel = ko.mapping.fromJS(#Html.Raw(Model.ToJson()));
var extendViewModel = function () {
this.firstName = ko.computed({
read: function(){
return viewModel.fname();
},
write: function(value){
viewModel.fname(value);
},
owner: viewModel
});
};
viewModel = ko.mapping.fromJS(new extendViewModel(), viewModel);
ko.applyBindings(viewModel);
Then you can use firstName in your markup for bindings and viewModel.fname will be updated, too.
I am have a problem binding a JSON result with knockout js. Below is my code
var AddDeparmentViewModel = function() {
var self = this;
self.AddDepartmentModel = {};
$.getJSON('/EventTracker/Department/GetEmptyModel/', function(data) {
ko.mapping.fromJS(data, {}, self.AddDepartmentModel);
});
};
$(document).ready(function() {
var departmentViewModel = new AddDeparmentViewModel();
ko.applyBindings(departmentViewModel);
})
Here is my HTML:
<div class="titleWrapper">
Add Department
</div>
<label>Department Name:</label>
<input data-bind="value: AddDepartmentModel.DepartmentName" id="departmentNameTextbox" type="text" />
<p data-bind="text: AddDepartmentModel.DepartmentName"></p>
The values I am returning are not appearing. Could someone point out where my mistake is. In this case the server is returning a single object not an array of objects.
Thanks!
Edit:
The Server returns this JSON:
{"DepartmentID":0,"DepartmentName":"Test","EVNTTRKR_Admins":[],"EVNTTRKR_Event": [],"EVNTTRKR_ItemCategories":[]}
Edit:
Here is the function GetEmptyModel:
public JsonResult GetEmptyModel()
{
var eventT = new EVNTTRKR_Departments();
eventT.DepartmentName = "Test";
return Json(eventT, JsonRequestBehavior.AllowGet);
}
The problem you are having seems to be fairly common. You are creating observables after binding the viewmodel. When this happens there is nothing for knockout to hook into and nothing gets rendered. A fix for this would be to make sure AddDepartmentModel is an observable and to set it to the return value rather than overwritting it with the fromJS.
var AddDeparmentViewModel = function() {
var self = this;
self.AddDepartmentModel = ko.observable({}); //important to have a default value so bindings dont break
$.getJSON('/echo/json/', function(data){
var mapped = ko.mapping.fromJS(data);
self.AddDepartmentModel(data); // here we are pushing values into the observable
});
};
This also requires fixes to the bindings as they now need to invoke AddDepartmentModel as a function:
<input data-bind="value: AddDepartmentModel().DepartmentName" id="departmentNameTextbox" type="text" />
Example fiddle with json request and population in callback.
http://jsfiddle.net/infiniteloops/YWC9N/
I created a jsfiddle here and replaced your getJson call with your server data (because I cannot call your getJson url). And it all seems to work which leads me to believe that an error is occuring in the getJson call.
Could you open your browser developer tools and look for any errors in the console. If there is an error and you're not sure what it means, add the error information to your original problem description.
var AddDeparmentViewModel = function() {
var self = this;
self.AddDepartmentModel = {};
var data =
{"DepartmentID":0,"DepartmentName":"Test","EVNTTRKR_Admins":[],"EVNTTRKR_Event": [],"EVNTTRKR_ItemCategories":[]
};
ko.mapping.fromJS(data, {}, self.AddDepartmentModel);
};
$(document).ready(function() {
var departmentViewModel = new AddDeparmentViewModel();
ko.applyBindings(departmentViewModel);
})
So if your Controller Action returns a Model with pre-populated values, how do you make KnockoutJS aware of them?
E.g.:
#Html.TextBoxFor(m => m.Title, new { data_bind="value: title"} )
however, on $(document).ready() where I bind knockout.js ViewModel, this value isn't yet populated:
$(document).ready({
var viewModel = {
title: ko.observable($("#Title").val()) // too early for this?!
}
ko.applyBindings(viewModel);
});
How do you make KnockoutJS work with MVC's model binding?
One workaround I found was to set the JavaScript variable in my Razor View, like so:
<script>
var strTitle = '#Model.Title';
</script>
and than use it in the Knockout model binding. That works, but I hate it. What if your form has like hundreds of fields? You don't want as many JavaScript variables in your page.
Am I missing the obvious here?
This seems similar to this question. Normally you would set your view model by converting #Model to JSON in a script:
<script type="text/javascript">
var model = #(new HtmlString(new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(Model)));
</script>
You could also create your own binding handler that will initially load the view model based on control values. This new myvalue handler basically calls the existing value handler, except it updates the view model from the initial control value on init.
ko.bindingHandlers['myvalue'] = {
'init': function (element, valueAccessor, allBindingsAccessor) {
// call existing value init code
ko.bindingHandlers['value'].init(element, valueAccessor, allBindingsAccessor);
// valueUpdateHandler() code
var modelValue = valueAccessor();
var elementValue = ko.selectExtensions.readValue(element);
modelValue(elementValue); // simplified next line, writeValueToProperty isn't exported
//ko.jsonExpressionRewriting.writeValueToProperty(modelValue, allBindingsAccessor, 'value', elementValue, /* checkIfDifferent: */ true);
},
'update': function (element, valueAccessor) {
// call existing value update code
ko.bindingHandlers['value'].update(element, valueAccessor);
}
};
Then when you call ko.applyBindings, your observable will be set based on the control's value initially:
<input type="text" data-bind="myvalue: Title" value="This Title will be used" />
<input type="text" data-bind="value: Title" value="This will not be used" />
<!-- MVC -->
#Html.TextBoxFor(m => m.Title, new { data_bind="myvalue: Title"} )
SAMPLE FIDDLE
What about simply serializing your entire page model to json using JSON.NET or similar. Then your page will be populated via normal razor view bindings for non-js users. Then your page scripts can be something like:
<script>
ko.applyBindings(#Html.ToJSON(Model));
</script>
Or if you have a typed viewModel
<script>
var viewModel = new MyViewModel(#Html.ToJSON(Model));
ko.applyBindings(viewModel);
</script>
It makes sense to structure your client side and actual view models the same so no manipulation of the json shape is required.
EDIT
Example of the toJSON helper.
public static MvcHtmlString ToJson(this HtmlHelper html, object obj)
{
JavaScriptSerializer serializer = new JavaScriptSerializer();
return MvcHtmlString.Create(serializer.Serialize(obj));
}
Hope this helps.
Because I don't have a 50 point reputation to add a comment to the Jason Goemaat answer, I decided to add my comment here as an answer.
All the credits go to Jason Goemaat.
I wasn't able to make the code work for me. So I had to make a small change.
ko.bindingHandlers['myvalue'] = {
'init': function (element, valueAccessor, allBindingsAccessor) {
//get initial state of the element
var modelValue = valueAccessor();
var elementValue = ko.selectExtensions.readValue(element);
// call existing value init code
ko.bindingHandlers['value'].init(element, valueAccessor, allBindingsAccessor);
//Save initial state
modelValue(elementValue);
},
'update': function (element, valueAccessor) {
// call existing value update code
ko.bindingHandlers['value'].update(element, valueAccessor);
}
};
if I had this line at the top,
// call existing value init code
ko.bindingHandlers['value'].init(element, valueAccessor, allBindingsAccessor);
It was deleting the original state of the element. So whatever value I had in the input field, it was being deleted.
Inside the model I have this:
//publishing comment
self.publishingComment = ko.observable();
And my MVC looks like this
#Html.TextBoxFor(model => model.Comment, new { data_bind = "myvalue: publishingComment" })
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>