res.render - passing parameters dynamically - json

I'm trying to figure out how to render dynamically depending on a number of parameters in an object. Let's create a JSON example
var json =
[
{
"param_1":11,
"param_2":22
},
{
"param_1":33,
"param_2":44
}
]
And here is how I would pass the parameters if var json was static:
res.render("template.hbs", {
item_0_param_1: json[0].param_1
item_0_param_2: json[0].param_2,
item_1_param_1: json[1].param_1
item_1_param_2: json[1].param_2
}
The question that I have is - how can I pass parameters from variable 'json' if it is not static? I was thinking about doing a loop inside render, but I didn't know how would I return assigned parameters. Would appreciate the help. Thanks!

Related

How to parse dynamic json data in WebAPI controller from jqgrid edit url

In after inline edit free jqgrid sends variable number of columns to ASP.NET MVC4 WebAPI controller using POST method.
Posted data contains json string below.
json string posted to controller in POST body looks like:
{"Toode":"","Kogus":"0.0000",
"Nimetus":"1","Mootyhik0_nimetus":"",
"Reanr":"2",
"_oper":"edit","_rowid":"1673",
"_dokdata":"[
{\"name\":\"Maksetin1_tingimus\",\"value\":\"\"},
{\"name\":\"Kinnitatud\",\"value\":\"False\"}]"
}
It has 3 regions of properties:
Order details. Dynamic properties "Toode":"","Kogus":"0.0000","Nimetus":"1","Mootyhik0_nimetus":"",
"Reanr":"2"
This list may change on runtime depending on user preferences.
This is created by using jqgrid extraparam: getDetails() setting.
Fixed properties stating with underscore `"_oper":"edit","_rowid":"
Those are
_oper and _rowid are always present
jqgrid adds them automatically.
Order data. fixed property _dokdata which contains json array of dynamic properites {\"name\":\"Maksetin1_tingimus\",\"value\":\"\"},{\"name\":\"Kinnitatud\",\"value\":\"False\"}
This is created from jqgrid colmodel.
This list may change in runtime and may contain same poperty names as in p.1 order details.
How to get this data in controller ? Probably it shoud be parsed into two dictionaries . Is it possible to force WebAPI to pass this data as classes/collection to controller or should it parsed manually?
jqgrid settings are from answer Using jqGrid's inline-editing with RESTful urls?
Those and serialize methods can changed if this makes data passing more reasonable.
Resulting WebAPI should have easily understandable data format (good API) since it will be used by third party applications also.
$.extend($.jgrid.defaults, {
ajaxRowOptions: { contentType: "application/json", async: true },
serializeRowData: function (data) {
var propertyName, propertyValue, dataToSend = {};
for (propertyName in data) {
if (data.hasOwnProperty(propertyName)) {
propertyValue = data[propertyName];
if ($.isFunction(propertyValue)) {
dataToSend[propertyName] = propertyValue();
} else {
dataToSend[propertyName] = propertyValue;
}
}
}
return JSON.stringify(dataToSend);
}
});
Update
serializeRowData is changed to
serializeRowData: function (data) {
return JSON.stringify({
headerData: $("#_form").serializeArray(),
rowData: data
} );
}
This produces bloated json for headerData:
{"headerData": [
{"name":"Tasudok","value":"134"},
{"name":"Kuupaev","value":"2015-11-23"},
{"name":"Dokumnr","value":"135319"}
],
"rowData": {"Toode":"",
"Kogus":"0.0000",
"Nimetus":"öäölä<a",
"_rowsum":"0.00",
"Id":"1639",
"Dokumnr":"135319",
"_oper":"edit",
"_rowid":"1639"
}
}
How remove name and value properties from headerData so that it contains property name and value pairs like in rowData:
headerData: {
"Tasudok": "134",
"Kuupaev": "2015-11-23",
"Dokumnr": "135319"
}

Retrieve data without _id and _ref from coucgdb

I have a database with lots of document and i am using field type to define it as a table. I want to populate angularjs ui-grid with the JSON data coming in value. So i have created a view:
function(doc) {
if(doc.type === 'userTable'){
emit(doc._id, {userName:doc.userName,fName:doc.fName});
}
}
When i hit the url http://127.0.0.1:5984/rpt_db/_design/Dsgn_userjson/_view/Vw_userjson/ it gives me :
{"total_rows":1,"offset":0,"rows":[
{"id":"f43a147cd5c961fcfe4e1da1b800013a",
"key":"f43a147cd5c961fcfe4e1da1b800013a",
"value":{"userName":"rp670249","fName":"Ranjeeth"}}
]}
Now in my client code i need to do a loop and make data as JSON.
result.rows.forEach(function(item) {
var temp = { "id": item.value.userName, usrName: item.value.fName};
console.log(temp);
//Update data of grid using temp variable.
});
Is there an easy way so that i can directly use what's coming as part of couchdb JSON output which can be used as is in angular ui-grid.
You can refer column values using json dot notation in the columnDefs. Since your actual values are inside "value". you can create column definition like this,
$scope.myData = {"total_rows":1,"offset":0,"rows":[
{"id":"f43a147cd5c961fcfe4e1da1b800013a",
"key":"f43a147cd5c961fcfe4e1da1b800013a",
"value":{"userName":"rp670249","fName":"Ranjeeth"}}
]}
$scope.gridOptions = {
data : $scope.myData.rows,
columnDefs : [
{name:"id",field:"value.userName"},
{name:"usrName",field:"value.fName"}
]
};
Here's a working plnkr.
http://plnkr.co/edit/juLZeT6I0LOlek4QnMSP?p=preview

Collecting a value from JSON file with ember.js

I am trying to pass a simple variable value into an HTML file using ember.js. My value is contained within a json file called value.json.
My HTML code is as follows:
<h1>I won {{App.moneyvalue}} today!</h1>
However when I pass the json call via ember, it think that the entire call is a variable:
App = Ember.Application.create({
moneyvalue: function () {
return $.getJSON( "js/value.json", function( data ) {
return data.tot;
});
}
}
And returns the following:
I won function () { return $.getJSON( "js/donors.json", function( data ) { return data.tot; }); } today!
As it seems to think that moneyvalue is a string variable as opposed to a value?
The jSON file is superbasic
{
"tot": 100
}
Where is this going wrong?
you're supplying Handlebars with a function, generally you would use a computed or normal property on the object. In this case you really just shouldn't define it in the application scope either, I'd recommend using an application route (it's the root route of your app).
App.ApplicationRoute = Ember.Route.extend({
model: function(){
return $.getJSON( "js/value.json");
}
});
Then in your handlebars just use
<h1>I won {{tot}} today!</h1>
Here's an example: http://emberjs.jsbin.com/OxIDiVU/576/edit

parse urls in Backbone.js

I am new to Backbones.js, and I was trying to get my JSON urls and parse them correctly.
This is my code:
window.Post = Backbone.Model.extend({
initialize: function(options) {
this.id = options.id;
},
url: function() {
return 'api/get_post/?post_type=movies&id=' + this.id;
},
parse : function(response) {
return response.posts;
},
});
window.Posts = Backbone.Collection.extend({
model: Post,
defaults: {
model: Post,
},
url: "api/get_recent_posts/?post_type=movies",
parse : function(response) {
return response.posts;
},
});
It seems that parsing for both overrides each other or something. when I remove the parse option from the Post class, I get a full response from the collection, but not from the model.
Are there any clear examples on how to set parsing for different son hierarchies? my JSON result have a status ok before it dives into the actual data.
I've never used bones.js but maybe these examples will help.
I think what you want to do is get rid of the parse() function in your collection. This assumes that since it is a Post collection, your data will come in as an array of Post JSON objects [{id:'1', 'sub':{data}},{id:'2', 'sub':{data}},{id:'3', 'sub':{data}}] or something like that.
If your Post model has sub-models or collections, your model parse() will then take the sub-object property name and do something with it.
// In Post Model definition
parse:function(response) {
if (response.sub) {
// create some model or collection etc.
}
}
You might have to pass an option parse:true when you do your collection fetch.
I posted something along these lines which might help you see how sub-models can be instantiated on fetch calls.
Backbone.js: Load multiple collections with one request
Cast/initialize submodels of a Backbone Model
I hope this helps.

asp.net mvc 3 ViewModel collection property to json not working

Good evening everyone. I am currently using MVC 3 and I have a viewmodel that contains a property that is a List. I am currently using json2's JSON.stringify method to pass my viewmodel to my action method. While debugging I am noticing that all the simple properties are coming thru but the collection property is empty even though I know for sure that there is at least one object in the collection. I wanted to know if there is anyone that is running into the same issue. Below is the code that I am using to post to the action method:
$.post("/ReservationWizard/AddVehicleToReservation/",
JSON.stringify('#ViewData["modelAsJSON"]'),
function (data) {
if (data != null) {
$("#vehicle-selection-container").html(data);
$(".reservation-wizard-step").fadeIn();
}
});
The object #ViewData["modelAsJSON"] contains the following json and is passed to my action method
{"NumberOfVehicles":1,"VehiclesToService":[{"VehicleMakeId":0,"VehicleModelId":0}]}
As you can see the property "VehiclesToService" has one object but when it gets to my action method it is not translated to the corresponding object in the collection, but rather the collection is empty.
If anyone has any insight into this issue it would be greatly appreciated.
Thanks in advance.
UPDATE
OK after making the recommended changes and making the call to new JavaScriptSerializer().Serialize(#Model) this is the string that ultimately gets sent to my action method through the post
'{"NumberOfVehicles":1,"VehiclesToService":[{"VehicleMakeId":0,"VehicleModelId":0}]}'
I can debug and see the object that gets sent to my action method, but again the collection property is empty and I know that for sure there is at least one object in the collection.
The AddVehicleToReservation action method is declared as follows:
public ActionResult AddVehicleToReservation(VehicleSelection selections)
{
...
return PartialView("viewName", model);
}
Here's the problem:
JSON.stringify('#ViewData["modelAsJSON"]')
JSON.stringify is a client side function and you are passing as argument a list that's stored in the ViewData so I suppose that it ends up calling the .ToString() and you have
JSON.stringify('System.Collections.Generic.List<Foo>')
in your final HTML which obviously doesn't make much sense. Also don't forget that in order to pass parameters to the server using the $.post function the second parameter needs to be a javascript object which is not what JSON.stringify does (it generates a string). So you need to end up with HTML like this:
$.post(
'ReservationWizard/AddVehicleToReservation',
[ { id: 1, title: 'title 1' }, { id: 2, title: 'title 2' } ],
function (data) {
if (data != null) {
$('#vehicle-selection-container').html(data);
$('.reservation-wizard-step').fadeIn();
}
}
);
So to make this work you will first need to serialize this ViewData into JSON. You could use the JavaScriptSerializer class for this:
#{
var myList = new JavaScriptSerializer().Serialize(ViewData["modelAsJSON"]);
}
$.post(
'#Url.Action("AddVehicleToReservation", "ReservationWizard")',
// Don't use JSON.stringify: that makes JSON request and without
// proper content type header your sever won't be able to bind it
#myList,
function (data) {
if (data != null) {
$('#vehicle-selection-container').html(data);
$('.reservation-wizard-step').fadeIn();
}
}
);
And please don't use this ViewData. Make your views strongly typed and use view models.