JavaScript比较ViewData列表值与DropDownlist选定项目
问题描述:
我已经搜索周围的这个问题的答案,但没有完全满足我在找什么。 我有一个项目的下拉列表。当用户选择一个项目时,我想比较选定的值与2个不同列表中的项目(都从数据库填充并存储在ViewData中)。这样,我可以根据哪些列表项匹配来填充其他表单数据。我想做这个客户端(即,使用JQuery/Javascript)。 这篇文章看起来像一个良好的开端,但我需要用的物品在2名不同的列表比较我值为1: Need simple example of how to populate javascript array from Viewdata listJavaScript比较ViewData列表值与DropDownlist选定项目
答
最终得到的回答了我的问题。在我的.cshtml文件的形式第一节有:
@Html.DropDownList("DropDownCompany", (ViewData["DropDownCompanies"] as SelectList), "Select a Company")
在我的.cshtml文件的JavaScript的部分,我有:
$('#DropDownCompany').change(function() {
var dropdownvalue = $('#DropDownCompany').val();
// This is a list of objects
var str2 = @Html.Raw(Json.Encode(ViewData["CompaniesData"]));
然后,我以后可以(仍然JavaScript的部分内)通过以下方式比较:
// CompanyKey is a field of the CompaniesData class
for(var i in str2) {
if (str2[i].CompanyKey == dropdownvalue) {
// Do Stuff
}