Use variable with ViewData Instead of literal string - javascript

Is it possible to use a variable in place of the string literal for ViewData? What I have is this ...
var listsource = <% = ViewData["dtYears"] %>;
And what I'd like to do is something like this ...
var datasource = "dtYears";
var listsource = <% = ViewData[datasource] %>;
The reason I'd like do this so so I can have a generic function in my javascript that loads the list I specify with the datasource I specify (both via a parameter). Then I can have a generic LoadList function like so ...
function LoadList(datasource, target) {
// generic list population code goes here
}

You can try this approach:
//On your server code(controller) where you set the ViewData
// Convert the datasource List/object to a json string and add the string to ViewData
ViewData["dtYears"] = JsonConvert.SerializeObject(lstYears);
//On your Client html code (view)
//convert it to equavalent json object/objects, using one of the following two methods
var datasource = eval("(" + '<%=ViewData["dtYears"].ToString() %>' + ")");
//OR use jquery method
var datasource =jQuery.parseJSON('<%=ViewData["dtYears"].ToString() %>');
//you should be good to go
alert(datasource.length+ " objects in "+ datasource );

Yes, as far as I know that should work. Have you tried it and not gotten results you'd like?

Related

How to use json string after Serialization in view javascript?

I want to serialize a JSON string but when I pass JSON to view I see that my properties in code are in string format, that's probably why my code didn't work.
Serialization of my code in code behind:
var data = new ChartData
{
labels = new ChartLabels
{
labels = new string[3] {"Open", "Close", "Nothing"}
},
datasets = new ChartDatasets
{
data = new int[3] {20, 10, 3},
backgroundColor = new string[3] {"#ccf9d6", "#ccf9d6", "#ccf9d6"},
borderWidth = 1
}
};
var json = new JavaScriptSerializer().Serialize(data);
ScriptManager.RegisterStartupScript(
this,
GetType(),
"ServerControlScript",
"addChart(" + json + ");",
false);
And I want to use it in my JavaScript function:
function addChart(data) {
var ctx = document.getElementById("myChart");
var myChart = new Chart(ctx, data);
EDIT:
Json looks like below:
{"labels":
{
"fontSize":0,
"boxWidth":0,
"labels":["Open","Close","Nothing"]},
"datasets":{"label":null,"data":[20,10,3],
"backgroundColor":["#ccf9d6","#ccf9d6","#ccf9d6"],
"borderWidth":1
}
}
Is there any way to convert it to correct format? Or just put it to a JavaScript variable?
As stated on MDN,
The JSON.parse() method parses a JSON string, constructing the
JavaScript value or object described by the string.
Seeing as the addChart javascript method call is being executed, but is getting a string instead of the expected JSON object, that string has to be parsed.
Without knowing the broader context of the application it is hard to give a great answer as there are a few ways you could accomplish your goal. The simplest though would be to change the line "addChart(" + json + ");", to "addChart(JSON.parse(" + json + "));", so that when the application executes this javascript, the json string will be parsed by the javascript engine and made into a javascript object the addChart method is expecting.
I am not hip to the ScriptManager and I kind of like things to appear as I expect when I do my debugging in Chrome so this is how I would attack it using an asp:Literal on the page.
ASP Page:
<script src="assets/js/bootstrap.js" type="text/javascript">
</script>
<asp:Literal runat="server" ID="aspchartdata"></asp:Literal>
Code Behind:
var data = new ChartData
{
labels = new ChartLabels
{
labels = new string[3] {"Open", "Close", "Nothing"}
},
datasets = new ChartDatasets
{
data = new int[3] {20, 10, 3},
backgroundColor = new string[3] {"#ccf9d6", "#ccf9d6", "#ccf9d6"},
borderWidth = 1
}
};
aspchartdata.Text = "<script> var data=" + JsonConvert.SerializeObject(data); + "</script>";
Now you have a data variable in Javascript to use.
On the server side your literal is replaced by your new script to define the variable and now you can handle the onload running and such from within the ASPX page in a neat fashion.

how can i convert my data in javascript server side to json object and array?

i'm working with xpages and javascript server side i want to convert the fields in format json then i parse this dat and i put them in a grid,the problem is that these fields can contains values :one item or a list how can i convert them in json ?
this is my code :
this.getWFLog = function ()
{
var wfLoglines = [];
var line = "";
if (this.doc.hasItem (WF.LogActivityPS) == false) then
return ("");
var WFLogActivityPS = this.doc.getItem ("WF.LogActivityPS");
var WFActivityInPS = this.doc.getItem ("WFActivityInPS");
var WFActivityOutPS = this.doc.getItem ("WFActivityOutPS");
var WFLogDecisionPS = this.doc.getItem ("WF.LogDecisionPS");
var WFLogSubmitterPS = this.doc.getItem ("WF.LogSubmitterPS");
var WFLogCommentPS = this.doc.getItem ("WF.LogCommentPS");
var WFLogActivityDescPS = this.doc.getItem ("WF.LogActivityDescPS");
var Durr =((WFActivityOutPS-WFActivityInPS)/3600);
var json= {
"unid":"aa",
"Act":WFLogActivityPS,
"Fin":WFActivityOutPS,
"Durr":Durr,
"Decision":WFLogDecisionPS,
"Interv":WFLogSubmitterPS,
"Instruction":WFLogActivityDescPS,
"Comment":WFLogCommentPS
}
/*
*
* var wfdoc = new PSWorkflowDoc (document1, this);
histopry = wfdoc.getWFLog();
var getContact = JSON.parse(histopry );
*/ }
Careful. Your code is bleeding memory. Each Notes object you create (like the items) needs to be recycled after use calling .recycle().
There are a few ways you can go about it. The most radical would be to deploy the OpenNTF Domino API (ODA) which provides a handy document.toJson() function.
Less radical: create a helper bean and put code inside there. I would call a method with the document and an array of field names as parameter. This will allow you to loop through it.
Use the Json helper methods found in com.ibm.commons.util.io.json they will make sure all escaping is done properly. You need to decide if you really want arrays and objects mixed - especially if the same field can be one or the other in different documents. If you want them flat use item.getText(); otherwise use item.getValues() There's a good article by Jesse explaining more on JSON in XPages. Go check it out. Hope that helps.
If an input field contains several values that you want to transform into an array, use the split method :
var WFLogActivityPS = this.doc.getItem("WF.LogActivityPS").split(",")
// input : A,B,C --> result :["A","B","C"]

How to replace ' / ' with '-' inside ObservableArray ? Knockout js

Well i am trying to pass an observable array via ajax call to my controller but i get every value there except date . i get something like '01-01-01' etc .
I found the issue but unable to fix that as i dont know how to replace / with - .
My ObservableArray have around 10 list items each list item holds a many properties out of those startDate holds the date like ("23/10/2014") . i just need something like ("23-10-2014") .
Tought of posting my function's and more i hope thats not required in this case i believe .
Let me explain with bit of code and sample data :
function myarray()
{
var self=this;
self.startDate=ko.observable("");
self.name=ko.observable("");
self.place=ko.observable("");
}
MyObservableArray :
self.Main= ko.observableArray();
In between i do some stuff to load Data into self.Main and i am sending self.Main to controller having data like below :
self.Main[0] holds :
startDate() -->gives you "23/10/2014" //individual observables inside onservable array
name() --> "jhon"
place()--> "croatia"
Likely
self.Main[9] holds :
startDate() --> "29/05/2012"
name() --> "pop"
place()--> "usa"
I am trying like i want to alter the self.Main() and replace the startDate and use the same self.Main to send to my controller . Once after replacing in self.Main when i check date the / should be replaced with - .
Possible solution : i can use a different observable array and push all the VM's of Main into it but i am trying to do on self.Main without using other .
If someone can show some light it is much appreciated .
What I got that you are facing problem in escaping / in replace.
Try this
"(23/10/2014)".replace(/\//g,"-") //returns "(23-10-2014)"
I tried something for you using simple JS
var arr = [{date:"(23/10/2014)"},{date:"(23/10/2014)"},{date:"(23/10/2014)"},{date:"(23/10/2014)"}];
arr.forEach(function(obj){obj.date = obj.date.replace(/\//g,"-")});
console.log(arr) //will print date field as "(23-10-2014)" for all objects.
One solution would be to add a computed value that returns the array with the right values.
self.Main = ko.observableArray([...values here...]);
self.MainComputed = ko.computed(function() {
var computedArray = [];
self.Main().forEach(function(item) {
var newItem = myarray(); //Create a new item.
newItem.name(item.name());
newItem.place(item.place());
newItem.startDate(item.startDate().replace(/\//g,"-"));
computedArray.push(newItem);
});
return computedArray;
});
Then use the computed value in the places where you need the values with -.
I can think of two other ways to solve your issue, when taken into account that you want to use self.Main:
Replace the / with - before setting startDate on your item.
Change startDate to a computed value while storing the original value in another variable.
The first solution should be pretty straight forward (provided that it is a valid solution).
The second solution would look something like this:
function myarray()
{
var self=this;
self.originalStartDate = ko.observable("");
self.name = ko.observable("");
self.place = ko.observable("");
self.startDate = ko.computed(function() {
if(self.originalStartDate()) {
//We can only replace if the value is set.
return self.originalStartDate().replace(/\//g,"-");
}
else {
//If replace was not possible, we return the value as is.
return self.originalStartDate();
}
});
}
Now when you set the values you do something like:
var item = myarray();
item.originalStartDate = "01/01/2014";
Then when you get the value of startDate you would get "01-01-2014".
I haven't used Knockout.js but you can do this with a Javascript replace:
var str = [your array value] ;
var res = str.replace("/", "-");
For more information:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace

How to check data is getting pushed into JSON or not

JSON
This is my JSON structure. I am pushing data into this on button click.
var arrtopic = {
"info" : []
};
JS
I wrote this is function
arrtopic.info.push({
"Name" :name,
"Number" : num
});
JS for json data display
function displayJson(){
var obj = eval ("(" + arrtopic + ")");
document.getElementById("newme").innerHTML=obj.info.Name;
}
This is not working, please suggest something
Thank you in advance for your help
Try this
function displayJson(){
document.getElementById("newme").innerHTML= arrtopic.info[0].Name;
}
You are doing correct just use
console.log(arrtopic.info[0].Name);
instead of arrtopic.info.Name
function displayJson(){
var obj =JSON.parse(arrtopic);
document.getElementById("newme").innerHTML=obj.info.Name;
}
You can also use alert(obj.count); to fine whether the items are being pushed into

Pass Array from MVC to javascript?

I can pass a variable from MVC ASP.NET by using this :
var lastCategoryId = '<%=Model.CS.LastSelectedCategory %>';
This work fine with string or integer but how do I do with an array of strings? I have tried to pass the array the same way but the variable is set to System.String[] ?
You could let .NET handle all the heavy lifting for you with this simple line of code.
This assumes you're using MVC Razor syntax.
var yourJavaScriptArray = #Html.Raw(Json.Encode(Model.YourDotNetArray));
For newer versions of MVC, use:
var yourJavaScriptArray = #Html.Raw(Json.Serialize(Model.YourDotNetArray));
You could JSON serialize it. This way could could pass even more complex values and not worry about escaping simple quotes, double quotes, etc :
var categoriesList = <%= new JavaScriptSerializer().Serialize(new[] { "value1", "value2" }) %>;
Writing an HTML helper to do this would be even better:
public static class HtmlExtensions
{
public static string JsonSerialize(this HtmlHelper htmlHelper, object value)
{
return new JavaScriptSerializer().Serialize(value);
}
}
and then in your view:
<script type="text/javascript">
var categoriesList = <%= Html.JsonSerialize(new[] { "value1", "value2" }) %>;
</script>
This should do
var someArray=[<%foreach (var s in myStringArray){%>'<%=s%>',<%}%>];
something like this:
<script type="text/javascript">
var myArr = [<%=string.Join(",", strArr.Select(o => "\"" + o + "\"")) %>];
</script>
One liner:
var data = [#Html.Raw(String.Join(",", Model.MyArray.Select(i => "'" + i + "'")))];
So easy, so simple
<script type="text/javascript">
var array = #Html.Raw(
Json.Encode(
(Model).Select(m=> new
{
id= m.ID,
name=m.Name
})
)
);
</script>
Output is:
[{"id":1,"name":"Name of 1"}, {"id":2,"name":"Name of 2"}, ...];
Using Json.NET
var yourlist = JSON.parse('#Html.Raw(JsonConvert.SerializeObject(Model.YourList))');
You need to format the array into a JavaScript array syntax.
var someArray = [<%= Model.SomeArray.Select(x => "'" + x +"'")
.Aggregate((x,y) => x + ", " + y); %>];
This will surround each entry by single quotes and then join them together with commas between square brackets.
Updated: removed extra parenthesis.
Just wanted to provide an answer using Razor syntax:
We have a Dictionary<int, int> that we are rendering for a jQuery Sparkline, in the form of "an array of arrays".
var usageData = [ #string.Join(",", Model.UsageData.Select(d => string.Format("[{0},{1}]", d.Key, d.Value)).ToArray()) ];
Which is used like so:
$('#sparkline').UsageSparkline(usageData, { tooltipFormatter: cachedTooltips });
This is what we get when viewing the source:
var usageData = [ [-13,0],[-12,1],[-11,0],[-10,0],[-9,1],[-8,1],[-7,0],[-6,2],[-5,2],[-4,0],[-3,0],[-2,9],[-1,3],[0,4] ];
$('#sparkline').UsageSparkline(usageData, { tooltipFormatter: cachedTooltips });

Categories

Resources