Pass Array from MVC to javascript? - 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 });

Related

Razor inside javascript key value declaration?

Given the need to extract data from a viewdata into a javascript key/value object:
var stuff = {
something : [#someVar.Prop2, #someVar.Prop3, etc]
};
I want to make the key have the "name" of someVar.Prop1 so that:
var stuff = {
#someVar.Prop1 : [#someVar.Prop2, #someVar.Prop3, etc]
};
Yet when I use the form in the second code block above, I get a Expected identifier, string or number error at the colon:
#someVar.Prop1 : [#someVar.Prop2, etc]
---------------X (x marks the spot)
How do I need to format the razor code so that it knows what I'm trying to say?
You should definitely not be trying to build your JSON piece by piece in your Razor view. That can go wrong very easily.
To expand on #DLeh's answer, what you can do is build a dictionary of the values you want, serialize that into JSON right in your Razor view, and assign that to your variable as shown here:
#{
// Assume that someVar is provided from somewhere else;
// this is just for demonstration
var someVar = new { Prop1 = "My Prop", Prop2 = "Prop Value", Prop3 = 7 };
}
#{
var obj = new Dictionary<string, object>
{
{someVar.Prop1, new object[] { someVar.Prop2, someVar.Prop3 } }
};
}
<script>
var stuff = #Html.Raw(Json.Encode(obj));
</script>
Rendered output:
<script>
var stuff = {"My Prop":["Prop Value",7]};
</script>
You can surround razor expressions in quotes ' or " to have them output into a javascript block. If you need the type to be preserved properly, you can use methods like parseInt() or parseFloat() to do so.
Example:
var stuff = {
value1 : '#val1',
value2 : [ parseInt('#val2'), parseInt('#val3') ]
};
If you need to left side of the assignment to be variable, you will probably need to build a json string and then parse that into the object. Something like this, my quotes might be off.
var stuffJson = '{"#value1" : "#val1", "#value2" : "[ #val2, #val3 ]" }';
var stuff = JSON.parse(stuffJson);
If you're doing this a lot, you might want to consider using the Json() method in your controller to help you build these more easily. You could build a dictionary of key / value and have that output json:
public virtual ActionResult GetStuff()
{
string value1 = "key1",
value2 = "key2",
val1 = "str1",
val2 = "str2",
val3 = "str3";
var dict = new Dictionary<string, object>
{
{ value1, val1},
{ value2, new List<string> { val2, val3} },
};
return Json(dict, JsonRequestBehavior.AllowGet);
}
Output:
{"key1":"str1","key2":["str2","str3"]}
The answer is to ignore Visual Studio's complaint of the problem as the code runs and throws no error:
#country.CountryCode: ['#someVar.Prop1', '#someVar.Prop2', etc],

Use variable with ViewData Instead of literal string

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?

Error in adding element to array on view + MVC

Timeline.js + MVC + JavaScript
I am having the following code on my view
#{
var objs = objstudent.Timelines.Where(x => x.StudentID == Sessions.objStudent.StudentID).AsQueryable();
}
<script type="text/javascript">
#{
#:var data = [];
foreach(Student.Models.Timeline student in objs)
{
#:data.push({start : new Date "#student.MeetingDate", content : "#student.Description" });
}
}
here I am trying to add details in data array which will be used for displaying details in timeline, but when I check data's value in browser it shows me undefined.
I have tried using but problem is same.
any solution ?
Never build javascript literals manually like this. Always use proper serializers. For example:
#{
var objs = objstudent.Timelines.Where(x => x.StudentID == Sessions.objStudent.StudentID).AsQueryable();
}
<script type="text/javascript">
var data = #Html.Raw(
Json.Encode(
objs.Select(x => new
{
start = x.MeetingDate,
content = x.Description
})
)
);
</script>
should end up with something along the lines of:
<script type="text/javascript">
var data = [
{ "start": "\/Date(1334655137358)\/", "content": "foo" },
{ "start": "\/Date(1334655137358)\/", "content": "bar" },
...
];
</script>
Notice that the DateTime fields are serialized using the /Date(Ticks) format. You could use various techniques to convert them to native javascript dates.

How can I parse this home-made string-based data format?

I need to iterate through a dataset of IDs and labels. I got some part of the code right, but I need some assistance.
// 1. String
var string = '1:answer1,2:answer2,3:answer3,4:answer4,5:answer5,'
// 2. Split to array
var string = string.split(",");
// 3. EACH
$.each(string, function(key, val) {
var answer = answer.split(":");
$.each(answer, function(key1, val1) {
// output textfield with id of key1 and value of val1
});
});
I can go through the first set of data, that is comma separated, but not the next (:). How do I do that?
$.each(string, function(key, val) {
var answer = val.split(":");
key1 = answer[0];
val1 = answer[1];
alert(key1+"--"+val1);
});
it should be var answer= val.split(":"); instead of var answer = answer.split(":");
You can use String.replace as an iterator:
var string = '1:answer1,2:answer2,3:answer3,4:answer4,5:answer5,'
var html = []
string.replace(/([^:]+):([^,]+)(,|$)/g, function(_, key, val) {
html.push("<input name='" + key + "' value='" + val + "'>")
});
alert(html.join("\n"))
Nothing against your home-made string of course, but have you considered using JSON for encapsulating data in a string. While JSON is universally usable it is probably the perfect match for JavaScript.
So if you would encode your data as follows it would really be a piece of cake to parse:
var data = [
{
"id": 1,
"answer": "answer1"
},
{
"id": 2,
"name": "answer2.. etc."
}
];
So now you can access your data very easily using array and property notation:
alert (data[0].answer);
Update: So in if you are lucky and your Rails app is on version 3.1 then adding support for JSON is really a piece of cake:
For basic JSON support the only thing you need to do is this:
# GET /answers/1
# GET /answers/1.json
def show
#answer = Answer.find(params[:id])
respond_to do |format|
format.html # show.html.erb
format.json do
render json: #answer
end
end
end

How could I iterate the values in ArrayList in java from java script?

I have stored a bulk of objects in an ArrayList and I have set that in the request. Now I want to retrive the values in the Arraylist from my java script. Please help me with the solution
You can use JSON to facilitate the exchange of information between Java and Javascript. Libraries are available on both ends.
To put the elements of a List into an array, you can use Collection.toArray.
You need to serialize them as javascript first.
There are 2 ways to do it:
1) Universal way - https://stackoverflow.com/questions/338586/a-better-java-json-library
You just put in your jsp something like this:
<script...>
var myArray = <% JSON.Serialize(myArray) %>;
</script>
2) Fast and dirty:
<script...>
var myArray = [
<c:forEach items="${myArray}" var="item">
{
name = "<c:out value="${item.name}">",
text = "<c:out value="${item.text}">"
},
</c:forEach>
];
</script>
Both will result in Javascript like this, and can be used in JS:
var myArray = [
{
name = "Mike",
text = "Hello world"
},
{
name = "Max",
text = "Hi!"
}
];

Categories

Resources