Looping and comparing ViewData data with DropDownListFor using Jquery

别来无恙 提交于 2019-12-11 15:53:56

问题


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

  • Get each of this ViewData["ViewDataNames2"] strings;
  • Compare the name of each string with the name of a DropDownListFor;
  • If part of the name of the DropDownListFor matches one of the ViewData string name, I should print (eventually, I will do more work but for now I am trying to print it).

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"]));

回答1:


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...
}


来源:https://stackoverflow.com/questions/57273898/looping-and-comparing-viewdata-data-with-dropdownlistfor-using-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!