[英]Looping and comparing ViewData data with DropDownListFor using Jquery
通過控制器,我正在將一個ViewData以及其他幾個ViewData的名稱發送到我的View(.cshtml)。 在控制器方面,我很信任並以這種方式發送:
List<string> Names = new List<string>();
Names.Add(NameForViewBag.ToString());
ViewData["ViewDataNames2"] = Names;
因此,這將存儲我正在創建的ViewDatas的所有名稱。
然后,我正在苦苦掙扎的是如何在.cshtml端使用Jquery使用此ViewData。 我的想法是
在我的腳本中,我很成功地獲取了我的DropDownList的名稱。
console.log($("#SeriesTypeId option:selected").text().replace(" ", ""));
但是,這就是我陷入困境的地方。 我想做一些foreach循環,以將該下拉列表與ViewData [“ ViewDataNames2”]的每個字符串進行比較。 我試過的
像這樣檢索ViewData:
var yValue = "@ViewData["ViewDataNames2"]";
對於我的循環,我嘗試了這種方式:
@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數組,如下所示:
var xValue = JSON.parse('@Html.Raw(Newtonsoft.Json.JsonConvert.SerializeObject(ViewData["ViewDataNames"]))');
在JavaScript中將數組循環為:
for (var i = 0; i < xValue.length; i++) {
var obj = xValue[i];
//perform operation...
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.