Iterate over Dictionary with java-script selector - c#

I have a Dictionary in my view, there are
[inputID, tooltip].
Also i have a set of id's of my input elements in this page.
I need to iterate through the dictionary with my elements ids:
#{
Dictionary<string, string> questionMarks =
ViewBag.QuestionMarks as Dictionary<string, string>;
#}
<script type="java-script">
$(document).ready(function () {
var inputs = $('input,select[type!="hidden"]');
$.each(inputs, function(i, val) {
if ($(val).attr('id')) {
var id = $(val).attr('id');
var iter_string = '#questionMarks' + "[" + id + "]";
alert(iter_string); // [1]
alert('#questionMarks["cvc"]'); // here i got tooltip
}
});
</script>
[1] i have System.Collection.Generic.Dictionary`2[System.String, System.String][cvc]
Thanks to Jan Jongboom,
Finally i got that i wanted:
#using System.Web.Script.Serialization
#{
Dictionary<string, string> questionMarks = ViewBag.QuestionMarks as Dictionary<string, string>;
JavaScriptSerializer jss = new JavaScriptSerializer();
#}
<script type="text/javascript">
var questionMarks = #Html.Raw(jss.Serialize((Dictionary<string, string>)ViewBag.QuestionMarks));
$(document).ready(function () {
for ( keyVar in questionMarks ) {
$('#' + keyVar).attr('original-title', questionMarks[keyVar]);
$('#' + keyVar).tipsy({ gravity: 'w' });
}
});
</script>

Do something like
<script>
var questionMarks = #new JavaScriptSerializer().Serialize((Dictionary<string, string>)ViewBag.QuestionMarks) ;
</script>
Now you have a javascript variable called questionMarks that you can iterate over.

No, you can't iterate from the client side code through server variable. You can generate initialization code from JS variable (like JSON) or generate necessary html on the server side. Also you can requests for such data on from jsavascript via ajax request.

Attatching data attributes to the inputs as they are drawn should help you with this one.
Example: http://jsfiddle.net/Krch9/
$(document).ready(function(e) {
var inputs = $("input", "#container");
$.each(inputs, function(i, val) {
var ToolTipText = $(this).data('tooltiptext');
/// Run your tooltip plugin here ...
$("#output").html($("#output").html() + "<br>" + $(this).attr('id') + " : " + ToolTipText);
});
});
Using MVC helpers you can easily add them:
#Html.TextBoxFor(x => x.Field, new { data_tooltiptext = "Blah blah"});
The markup would end up looking something like this:
<input type="text" id="Field" data-tooltiptext="Blah blah">
Edit: Extra help
I.E Loop through your elements
foreach( var question in questionMarks) {
#Html.TextBox(question.Key, new { data_tooltiptext = question.Value} );
}
Then use the javascript example (Youll need to modify it to your needs ...) to run the plugin on the elements

To remove the quotes, use Html.Raw()
var questionMarks = '#Html.Raw(jss.Serialize((Dictionary<string, string>)ViewBag.QuestionMarks))';

Related

Passing jQuery dictionary object to an input field

var dictionary = [];
dictionary.push({
key:"Res01" ,
value: "Loss of internet connection at location"
});
when adding this dictionary object to an input field
$('#hdnNotesDict').val('');
$('#hdnNotesDict').val(dictionary);
i am not getting the dictionary value in that input field.
getting result as: [object,object]
Thanks in advance and any suggestion will be appreciated
Let's say you have this form in your view:
<form method="post">
<input id="kvps" name="kvps" />
<input id="submit" type="submit" value="Submit" />
</form>
and you put some values like that:
(function () {
$('#submit').mousedown(function () {
let input = $('#kvps');
let dict = [];
for (var i = 0; i < 10; i++) {
dict.push({ key: `Res${i}`, val: `Val${i}` });
}
input.val(JSON.stringify(dict));
});
})();
in this case you convert the array in a string and you should take it as string into your controller
BUT - you cannot convert it to dictionary immediately, first you should map it to array of model with the same property names then you can call ToDictionary over it.
Array example:
[HttpPost]
public IActionResult JInput(string kvps)
{
var arr = JsonSerializer.Deserialize<object[]>(kvps);
return this.View();
}
If you need it as Dictionary<string, string> you schould use in your jquery object instead:
(function () {
$('#submit').mousedown(function () {
let input = $('#kvps');
let dict = {};
for (var i = 0; i < 10; i++) {
// watch out for the keys here to not overwrite the values
dict[`Res${i}`] = `Val${i}`;
}
input.val(JSON.stringify(dict));
});
})();
And in your controller like that:
[HttpPost]
public IActionResult JInput(string kvps)
{
var arr = JsonSerializer.Deserialize<Dictionary<string, string>>(kvps);
return this.View();
}

Pass list from cshtml view to jquery function

Im trying to pass List that is generated from the following function;
public List<long> GetIDs()
{
var ids = new List<long>();
foreach(var s in student)
{
ids.Add(s.ID);
}
return ids;
}
and passing the list through the razor view and access the list in the jquery.
Following is the CSHTML code :
<a href="#" class="color-blue" data-studentids = "#schoolLicense.GetIDs()" onclick="sendWelcomeEmail(this)">
and this is the jquery code where I want to access the list and do actions from the ids I get ;
function sendWelcomeEmail(elem) {
$.each($(elem).attr("data-studentids"), function (index, value) {
alert(index + ": " + value);
});
}
But I'm not getting the Ids from the list instead of that I'm getting error as
TypeError: invalid 'in' operand obj
var length = !!obj && "length" in obj && obj.length,
Can anyone please let me know where Im going wrong?
Your problem is because by outputting the List<string> returned from your GetIDs method you're just coercing it to a string. Therefore your output is:
<a href="#" data-studentids="System.Collections.Generic.List`1[System.Int64]" ...
To fix this you can Join() the data together and then split() it back in to an array in your JS. Try this:
public List<long> GetIDs()
{
return student.Select(s => s.ID).ToList();
}
<a href="#" class="color-blue" data-studentids="#String.Join(",", schoolLicense.GetIDs())">
$('.colour-blue').click(function(e) {
e.preventDefault();
$(this).data('studentids').split(',').forEach(v, i) {
console.log(i + ": " + v);
});
});
Note the simplified use of LINQ in the GetIDs method, and the use of the unobtrusive event handler in the JS.
You can amend the .colour-blue selector in the jQuery object to better match your needs. I simply used it in this example as it was the only relevant attribute on the element.

Dynamically add objects to javascript array with Razor C#

Okay so I'm working with MVC4 in C# and I have to fill a javascript array with elements from the view's model. I'm trying to dynamically populate a Chart.js pie chart. This is my example code:
<script src="~/Scripts/Chart.js"></script>
<script type="text/javascript">
var data = [
{
value: 30,
color: "#F38630"
},
{
value: 50,
color: "#E0E4CC"
},
{
value: 100,
color: "#69D2E7"
}
]
//Get the context of the canvas element we want to select
var ctx = document.getElementById("myChart").getContext("2d");
var myNewChart = new Chart(ctx).Pie(data);
//Get context with jQuery - using jQuery's .get() method.
var ctx = $("#myChart").get(0).getContext("2d");
//This will get the first returned node in the jQuery collection.
var myNewChart = new Chart(ctx);
new Chart(ctx).Pie(data, options);
</script>
I want to be able to add elements to the data array in a for loop. I tried using .push like this
data.push([{
value: 30,
color: "#F38630"
}]);
But it stops the chart from being created entirely. Any idea how I can do something like:
foreach (var item in Model.List) {
data.add(item.value)
}
You can be even more awesome than that.
Create your own basic type to represent you Value/Color pair.
public class MyType
{
public string Value {get;set;}
public string Color {get;set;}
}
In your razor (or code behind) create an array for that type:
#{
var values = new List<MyType>();
// populate with some values.
JavaScriptSerializer js = new JavaScriptSerializer();
string json = js.Serialize(keyValues.ToArray());
}
Then in your Javascript:
<script type="text/javascript">
var data = #json; // TADA!!
//Get the context of the canvas element we want to select
var ctx = document.getElementById("myChart").getContext("2d");
var myNewChart = new Chart(ctx).Pie(data);
//... etc.
</script>
If you come across any problems serializing that list, I recommend using Json.Net to improve C# native serializers.
Your data is an array (see the brackets []).
Now you try to add an array with a single object to the array:
[{ value...
Just change it to an object {} and you will be fine.
{ value ... }

How to enter Razor within Javascript without quotes in ASP.NET MVC

I'm serializing my model:
<script type="text/javascript">
var Model = '#Model.ToJson()';
</script>
the ToJson is an extension method:
public static string ToJson(this object obj)
{
var serializer = new JavaScriptSerializer();
var val = serializer.Serialize(obj);
return val;
}
Now I want to access my model in other javascript files by doing:
var hello = Model.id;
The problem is that it doesn't serialize correctly when I use '#Model.ToJson()' because of the quotes.
The serialized object looks like this:
var Model = "{ "id": "2231f87c-a62c-4c2c-8f5d-b76d11942301" }";
But in order for me to access id by Model.id it should look like this:
var Model = { "id": "2231f87c-a62c-4c2c-8f5d-b76d11942301" };
How can I enter razor syntax without quotes? Using asp.net syntax I think it's:
var Model = <%=Model.ToJson() %>
How do I do the same with razor? Thanks!
If you use this JSON plugin you can do it all on the client and simply things. If you push up a JSON string, in javascript you could then do:
<script type="text/javascript">
var Model = JSON.parse("#Model.JsonString");
</script>
Since Razor by default escapes out the quotes, you need to use Html.Raw:
var Model = #Html.Raw(Model.ToJson());
It will turn that into:
var Model = {"id":"whatever"};
which is valid javascript.

Serialize Collection To JavaScript

I want to return serialized collection from code behind C# to javascript metod and then this javascript method to iterate normal all elements. I did this but the elements are iterated like normal string characters.
public string Alerts()
{
JavaScriptSerializer serializer = new JavaScriptSerializer();
IList<string> alerts = new List<string>();
alerts.Add("1");
alerts.Add("2");
string[] arrays = new string[] { "1", "2", "3" };
return serializer.Serialize(arrays);
}
<script type="text/javascript">
window.onload = function () {
alerts('<%= this.Alerts() %>');
};
</script>
I want the return value when iterates in js to be first index 1 second 2 thrit 3 etc. This here is not working normal.
You're encoding the serializer output:
public string Alerts()
will return
["1","2","3"]
When you go
alerts('<%= this.Alerts() %>');
You're saying
alerts('["1","2","3"]');
So skip the single quotes and you should be fine.
Try this
<script type="text/javascript">
window.onload = function () {
var arr = <%= this.Alerts() %>;
for (var i in arr)
alert(arr[i]); // Iterate over each element in array returned from C# code
};
</script>
Include jquery and try this
<script type="text/javascript">
window.onload = function () {
var arr = <%= this.Alerts() %>;
var arrList = JSON.parse(arr);
console.log(arrList);
};
</script>

Categories