5

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);
 }
Vivekh
  • 4,141
  • 11
  • 57
  • 102
ArDevTeam
  • 113
  • 1
  • 15

5 Answers5

1

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--
Vivekh
  • 4,141
  • 11
  • 57
  • 102
Pranay Rana
  • 175,020
  • 35
  • 237
  • 263
  • 1
    I guess you can be more clear on that whether the op has to write it in Scripts or in the html part . For that Answer you may be getting "list doesnot exists in the current context" error as I doubt that variable list will detected inside foreach – Vivekh Jun 25 '15 at 12:18
  • @Vivekh - may be you are correct i learning mvc and got syntax like this only – Pranay Rana Jun 25 '15 at 12:20
  • Okay but if you write this var jList = new Array(); in Html Markup it will print as it as so you should put that in code block or @ – Vivekh Jun 25 '15 at 12:29
  • No I dont think so because it wont be able to detect that jList is an javascript variable because as u used foreach it will assume that jList is a c# variable untill you specify it is a javascript variable by using @: or – Vivekh Jun 25 '15 at 12:49
  • @Vivekh - updated as per example i missed @: ...http://stackoverflow.com/questions/23781034/razor-mvc-populating-javascript-array-with-model-array – Pranay Rana Jun 25 '15 at 12:53
1

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)

sangram parmar
  • 8,462
  • 2
  • 23
  • 47
1

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>
Vivekh
  • 4,141
  • 11
  • 57
  • 102
1

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!

ArDevTeam
  • 113
  • 1
  • 15
0

Server Side

  public class users
        {        
            public string name{ get; set; }
        }

        // in your controller code
        ViewData["list"] = new List<users>(new users[] { new users() 
                          { name="prasad"}, new users() {name="raja"}});

Client Side

<script type="text/javascript">
$(function(){
    var myitems=JSON.parse('@Html.Raw(Json.Encode(this.ViewData["list"]))');

    $.each(myitems, function(index, item) {
      var name = item.name;
    });
});
</script>

i hope this may help you

Prasad Raja
  • 685
  • 1
  • 9
  • 37