user2960038
user2960038

Reputation: 1

Combine MVC .NET Razor with Javascript to build an array

I'm passing a List from my controller to a view, where I want to be able to take the Model and loop through results in JQuery/Javascript. I'm having a heck of a time figuring out how to do that.

My controller returns a list of colors. In the view, I converted the List to an array. I then pass it to my where I'm trying to loop through it to build an array I can using in my JS.

<script>
$(document).ready(function () {

    var currentView = sessionStorage.getItem('lastView');
    var jsArr;
    for (i=0; i<@arr.Length; i++) {
        jsArr.push(@arr[i])
    }

    if (!currentView) {
        sessionStorage.setItem('lastView', 0);
        $("body").css("background-image", "url('/Images/Home/@arr[0].Location')");
    } else {

        sessionStorage.setItem('lastView', currentView++);
    }
})
</script>

There has to be an easy way of doing this...

Upvotes: 0

Views: 1166

Answers (3)

AbdulG
AbdulG

Reputation: 755

Here is a way to manually build a JSON or JS object with razor code, some very easy to use code:

@foreach (var item in Model.Users)
    {
    <text>
    UserData[UserData.length] = {
        "UserID": '@item.ID', "FullName": '@item.Name'
    };
    </text>
    }

I purposefully showed model property names being used and JSON property names being different to show an advantage of manually building the array.

Also, in this case you would be able to send a model through with multiple collections of data. Then just iterate through that collection (@foreach (var item in Model.Users)) with your Razor code to build your JSON or Javascript object array

Upvotes: 0

TGH
TGH

Reputation: 39248

I would instead return json from the server. However if you want to do it in an html view I think something like this might work:

var jsonObj = '@Html.Raw(Json.Encode(Model.arr))'

//the loop is unnecessary, but can be useful if you need additional processing
var myArray = [];
for (i=0; i<jsonObj.length; i++) {
        myArray.push(jsonObj[i])
    }

Upvotes: 0

tvanfosson
tvanfosson

Reputation: 532435

<script>
$(document).ready(function () {

    var currentView = sessionStorage.getItem('lastView');
    var jsArr = @Html.Raw(Json.Encode(arr)) ;

    if (!currentView) {
        sessionStorage.setItem('lastView', 0);
        $("body").css("background-image", "url('/Images/Home/@Html.Raw(arr[0].Location)')");
    } else {

        sessionStorage.setItem('lastView', currentView++);
    }
})
</script>

Upvotes: 1

Related Questions