knockout js pass view param - asp.net-mvc

I have a parameter in my mvc view as
#{
var myparam = false;
}
I have my button in the same view as:
<input type="button" id="myButton" value="Click" class="btn btn-primary"
data-bind='enable: selectvalue() != ""' />
in the data-bind of my button I also want to check for myparam. Something like below:
data-bind='enable: filterCategory() != "" && !myparam'
How can I do that?
Thanks
Updated as below:
If my param is like below:
#{
var myparam = false;
}
And my JS:
<script>
var myData= #Html.Raw(Json.Serialize(Model));
myData.myParameter= "#myparam ";
</script>
My Knockout:
(function () {
var viewModel = function (data) {
var viemod= this;
viemod.myParam= vmData.myParam
}
}
If I use this myData in my knockout js as above it returns me "False" (string)
whereas it should be false (boolean)

That won't work because Razor runs server side. myparam is a C# local variable. So, you can't use it with knockout bindings which run client-side.
You can either create a javascript variable and assign the value like this:
<script>
var myparam = #Json.Encode(myparam);
</script>
or
If you don't want to pollute the global scope, add a myparam property to your viewModel.
var yourViewModel = function() {
var self = this;
self.myparam = #Json.Encode(myparam);
self.filterCategory = ko.observable('');
}
After update:
As mentioned before, it should be
myData.myparam = #Json.Encode(myparam);
But since you're going to .Serialize() the entire model, you can assign the myparam to a property in the controller itself.

Related

Knockoutjs binding JSON

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);
})

knockout.js, asp.net mvc4 - update simpel viewmodel with getJSON data

This is a newbie question and not to mention I am very new to knockout.js. All I am trying to do is, get details of a single Grower (Name, Company, Address) from the server and display it on the webpage. I am using $(document).bind('pageinit', function () since I'm using jQuery mobile.
Now my code is:
<h3><span data-bind="text: Name"></span></h3>
<span data-bind="text: Company"></span><br />
<span data-bind="text: Address"></span>
<script type="text/javascript">
$(document).bind('pageinit', function () {
function MyGrowerModel() {
//this.Name = "My Name";
//this.Company = "My Company";
//this.Address = "My Address";
//Load initial state from server, convert it to Task instances, then opulate self.tasks
$.getJSON("Grower/GetGrower", function (allData) {
this.Name = allData.Name;
this.Company = allData.Company;
this.Address = allData.Address;
alert(allData.Name); //works!
});
}
ko.applyBindings(new MyGrowerModel());
});
</script>
I am getting "Unable to parse bindings. Message: ReferenceError: Name is not defined; Binding value: Name
It makes sense because Name, Company and Address are scoped inside the getJSON function. So, my question is, where to declare those variables and how to update those ViewModel data?
I do not want to use the mapping plugin.
Any help is appreciated.
You're going to want to be using observable properties. That way, once your $.getJSON request finishes, your view will update with the new data.
<h3><span data-bind="text: Name"></span></h3>
<span data-bind="text: Company"></span><br />
<span data-bind="text: Address"></span>
<script type="text/javascript">
function MyGrowerModel() {
var self = this;
self.Name = ko.observable('');
self.Company = ko.observable('');
self.Address = ko.observable('');
self.Name.subscribe(function(newValue) {
alert("Name has changed: " + newValue);
});
//Load initial state from server and populate viewmodel
$.getJSON("Grower/GetGrower", function (allData) {
self.Name(allData.Name);
self.Company(allData.Company);
self.Address(allData.Address);
});
}
$(document).bind('pageinit', function () {
ko.applyBindings(new MyGrowerModel());
});
</script>
You need to preserve a reference to the object:
function MyGrowerModel() {
var self = this;
//Load initial state from server, convert it to Task instances, then populate self.tasks
$.getJSON("Grower/GetGrower", function (allData) {
self.Name = allData.Name;
self.Company = allData.Company;
self.Address = allData.Address;
});
}
That won't be the only problem though. $.getJSON is asynchronous by default, you'll either want to set async: false or change the callback function to apply the bindings. A better solution would be to use observables:
function MyGrowerModel() {
var self = this;
self.Name = ko.observable(''); // Value shown before getJSON returns
self.Company = ko.observable('');
self.Address = ko.observable('');
//Load initial state from server, convert it to Task instances, then populate self.tasks
$.getJSON("Grower/GetGrower", function (allData) {
self.Name(allData.Name);
self.Company(allData.Company);
self.Address(allData.Address);
});
}
This will initially display empty strings for each of Name, Company, and Address and will automatically update to the data returned from the getJSON call.

MVC Model Binding before KnockoutJS Model Binding

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" })

Knockout.js foreach binding value is not assigning to current object

I have a simple jsfiddle where i am trying to change value of each foreach binding. If I try to change value of a row then binding updates all other rows which I don't want. what wrong with this binding?
<div data-bind="foreach:lines">
<div>
<input data-bind="value: qty, valueUpdate: 'keyup'" />
<label data-bind="text: qty"></label>
</div>
var Product = function (qty) {
self = this;
self.qty = ko.observable(qty);
};
var Cart = function () {
self = this;
self.lines = ko.observableArray([]);
self.lines.push(new Product(1));
self.lines.push(new Product(2));
};
ko.applyBindings(new Cart());
UPDATE: I moved self.lines.push into cart model
The problem is that you're missing var from self = this. It needs to be var self = this. In your example, self is a global variable and each object is sharing the same self value.
Cart is your model:
var c = new Cart();
ko.applyBindings(c);
c.lines.push(new Product(1))
c.lines.push(new Product(2));​
http://jsfiddle.net/gY26k/

SPA Knockout JS Filter

I developed MVC 4 Single Page Application using ADO.Net as a data source. Trying to filter the view by ID, tried session variables without any luck. Here is the view code:
<script type="text/javascript" src="#Url.Content("~/Scripts/BloodPressuresViewModel.js")"></script>
<script type="text/javascript">
$(function () {
upshot.metadata(#(Html.Metadata<KOTest2.Controllers.DALController>()));
var viewModel = new MyApp.BloodPressuresViewModel({
serviceUrl: "#Url.Content("~/api/DAL")"
});
ko.applyBindings(viewModel);
});
</script>
and hee is the calss code in the Javascript file:
.....
var entityType = "BloodPressure:#KOTest2.Models";
MyApp.BloodPressure = function (data) {
var self = this;
// Underlying data
self.ID = ko.observable(data.ID);
self.PHN = ko.observable(data.PHN);
self.Day = ko.observable(data.Day);
self.Systolic = ko.observable(data.Systolic);
self.Diastolic = ko.observable(data.Diastolic);
self.HeartRate = ko.observable(data.HeartRate);
upshot.addEntityProperties(self, entityType);
}
.....
I think the best solution is to pass the ID using ViewBag to the view from the controller. Any idea how I can do that!!
Since I am not experienced programmer, will it be possible to filter (foreach)
<tbody data-bind="foreach: bloodPressures">
Thanks in advance.
I am not sure I understand how you access the database (on the server, right?) to do the filtering, but you could do something like this:
<table data-bind="foreach: rows">
<tr>
<td>id: <span data-bind="text: ID"></span></td>
<td>PHN: <span data-bind="text: PHN"></span></td>
....
</tr>
</table>
and in your javascript
function viewModel() {
var self = this;
this.loggedIn = ko.observable(false);
this.rows = ko.observableArray([]);
// return an array of objects to display to the user
function getDataFromServer() {
return ...;
}
ko.computed(function() {
if (this.loggedIn())
this.rows(getDataFromServer());
},this);
...
}
However you do your authentication, after it succeeds, execute this.loggedIn(true) which will cause the computed function to trigger the pull from the server and the setting of the this.rows(); this in turn will update the display.

Resources