使用Jquery循环和使用DropDownListFor比较ViewData数据 [英] Looping and comparing ViewData data with DropDownListFor using Jquery
问题描述
通过控制器,我正在将一个ViewData以及其他几个ViewData的名称发送到我的View(.cshtml).在控制器方面,我很信任并以这种方式发送:
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;
因此,它存储了我正在创建的ViewDatas的所有名称.
So, this stores all the name of the ViewDatas that I am creating.
然后,也是我苦苦挣扎的地方,是如何在.cshtml端使用Jquery使用此ViewData.我的想法是
Then, and where I am struggling, is how to work with this ViewData, using Jquery, on my .cshtml side. My idea is to
- 获取每个此ViewData ["ViewDataNames2"]字符串;
- 将每个字符串的名称与DropDownListFor的名称进行比较;
- 如果DropDownListFor名称的一部分与ViewData字符串名称之一匹配,我应该打印(最终,我会做更多的工作,但现在我正尝试打印它).
在我的脚本中,我很成功地获得了我的DropDownList的名称.
Inside my script, I am sucesufull getting the name of my DropDownListFor this way:
console.log($("#SeriesTypeId option:selected").text().replace(" ", ""));
但是,这就是我被困住的地方.我想做一些foreach循环,以将该下拉列表与ViewData ["ViewDataNames2"]的每个字符串进行比较.我尝试过的:
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:
像这样检索ViewData:
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>
}
我也尝试过这种方法:
// 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"]));
推荐答案
您需要序列化列表,然后使用Json.Parse
转换为JavaScript数组:
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"]))');
,并在JavaScript中将数组循环为:
and in JavaScript loop the array as:
for (var i = 0; i < xValue.length; i++) {
var obj = xValue[i];
//perform operation...
}
这篇关于使用Jquery循环和使用DropDownListFor比较ViewData数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!