I have a Generic List and I'm passing it as ViewData from my Controller to my .aspx View. I need to get and iterate it with a Jquery Script.
How could I make this script works?
Regards
success: function (result) {
var myArray = new Array();
var myArray = '<%: ViewData["List"] %>';
for (var i = 0; i < myArray.length; i++) {
alert(i);
}
You can do something like this..
<script type="text/javascript">
@{ List<string> ss = (List<string>)ViewData["List"];}
var myArray = [
@for (int i = 0; i < ss.Count; i++)
{
@: @(ss[i]),
}
]
</script>
my syntax for razor view(you can do it for classic)
Try like this , push items of list view to the array of javascript, wrap below code in script tag
--script tag--
var jList = new Array();
@foreach (var item in ViewData["List"] as List<String>)
{
@:jList.push('@item'); // That will work if its a one letter string but It doesnt know that its a string untill you use ''
}
--script tag--
Ok if you are using just a list of strings then
this will do
$(document).ready(function () {
@{List<string> listFromController = (List<string>)ViewData["List"];}
var myArray = [
@for (int i = 0; i < listFromController.Count; i++)
{
@: '@(listFromController[i])',
}
]
});
But if you are passing list of another type rather than string like an student Employee or a user you will need the following
Please use the appropriate class that you have passed and the properties suppose "UserName" could be "FirstName" "EmpId" or what ever
$(document).ready(function () {
@{ var listFromController = (List<KnockoutJSWebApi.Models.LoginViewModel>)ViewData["list"];}
var totalArray = [];
@for (int i = 0; i < listFromController.Count; i++)
{
<text>
var thisArray= {
'username': '@(listFromController[i].UserName)',
'password': '@(listFromController[i].Password)'
};
totalArray.push(thisArray);
</text>
}
});
Aspx View Engine syntax:
<script>
$(document).ready(function () {
<% List<string> listFromController = (List<string>)ViewData["List"]; %>
var myArray = [
<% for (int i = 0; i < listFromController.Count; i++){ %>
'<%: listFromController[i] %>',
<% } %>
]
debugger;
});
</script>
Problem solved. I used a JsonResult method in my Controller and returned the needed values as:
Json(List, JsonRequestBehavior.AllowGet);
With that, I don't need to iterate the values because I assign them as datasource to my DropDownList control.
$("#Generic_FK").data("DropDownList").dataSource.data(result);
Hope to help other people with the same issue!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With