jqueryrazorviewdata

Looping and comparing ViewData data with DropDownListFor using Jquery


Via controller, I am sending a ViewData to my View (.cshtml) with the name of several other ViewDatas. On the controller side, I am creding and sending this way:

List<string> Names = new List<string>();
Names.Add(NameForViewBag.ToString());
ViewData["ViewDataNames2"] = Names;

So, this stores all the name of the ViewDatas that I am creating.

Then, and where I am struggling, is how to work with this ViewData, using Jquery, on my .cshtml side. My idea is to

Inside my script, I am sucesufull getting the name of my DropDownListFor this way:

console.log($("#SeriesTypeId option:selected").text().replace(" ", ""));

But this is where I am getting stuck. I wanna do some sort of foreach loop to compare this dropdown with each string of the ViewData["ViewDataNames2"]. What I tried:

Retrieve the ViewData like this:

var yValue = "@ViewData["ViewDataNames2"]";

For my Loop I tried this way:

    @foreach (var myName in (List<string>)ViewData["ViewDataNames2"])
            {
            <td class="text-center">FormatName('@myName.NameOfViewData2', 1);</td>
            }

I also tried this approach:

    // If I try this way, on the console it will give error: SyntaxError: unexpected token: keyword 'class'
    /var xValue = @ViewData["ViewDataNames"];

    // If I try this way, on the console it will give error: SyntaxError: expected property name, got '&'
    //var check = @(Newtonsoft.Json.JsonConvert.SerializeObject(ViewData["ViewDataNames"]));

Solution

  • You need to serialize the list and then convert back to JavaScript array using Json.Parse as:

    var xValue = JSON.parse('@Html.Raw(Newtonsoft.Json.JsonConvert.SerializeObject(ViewData["ViewDataNames"]))');
    

    and in JavaScript loop the array as:

    for (var i = 0; i < xValue.length; i++) {
        var obj = xValue[i];
        //perform operation...
    }