asp.net mvc将ViewBag字典显示为javascript
我是C#asp.net mvc中的新成员。 我正在制作一个ViewBag,其中包含控制器中的Dictionary数据类型,我想通过.cshtml中的javascript获取并显示值,以便用googlemaps函数对其进行编码。
这里是我的控制器字典和视图代码:
Dictionary<string, string> alamatVehicleMarker = new Dictionary<string, string>();
alamatVehicleMarker.Add("v1","Bali");
alamatVehicleMarker.Add("v2","Jakarta");
alamatVehicleMarker.Add("v3","Bandung");
ViewBag.getAlamatVehicle = alamatVehicleMarker;
你能帮助我如何获得ViewBag.getAlamatVehicle和如何循环它请
EDITED
我试过这个:
<script>
function GetViewBagDictionary(id) {
@foreach (var item in ViewBag.getAlamatVehicle)
{
var key = item.Key;
var Value = item.Value;
if (key == id)
{
return Value;
}
}
return "not found";
}
<script>
但在if函数内部会出现一个错误: The name 'id' does not exist in the current context
像这样的东西只会小心数据类型
var dictionary = @Html.Raw(Json.Encode(ViewBag.getAlamatVehicle));
for(var key in dictionary ){
var value = dictionary[key];
console.log(value);
}
以下是我如何将VeiwBag转换为JavaScript的ViewBag对象
<script type="text/javascript">
var ViewBag = {
IsDesigner: ("@ViewBag.IsDesigner").toLowerCase() === 'true',
IsAdmin: ("@ViewBag.IsAdmin").toLowerCase() === 'true',
EmptyGuid: "@ViewBag.EmptyGuid",
Advertisers_ID: "@ViewBag.Advertisers_ID",
Primary_Category: "@ViewBag.Primary_Category",
Primary_Category_ID: "@ViewBag.Primary_Category_ID",
Advertiser_Name: "@ViewBag.Advertiser_Name",
Advertiser_NameMM: "@ViewBag.Advertiser_NameMM",
BookTypeName: "@ViewBag.BookTypeName",
getAlamatVehicle: {
@{
int marker_count = 0;
string markers_str = "";
foreach (var item in ViewBag.getAlamatVehicle)
{
markers_str += """ + item.Key + "": "" + item.Value + """;
marker_count++;
if (marker_count < ViewBag.getAlamatVehicle.Count)
{
markers_str += ", ";
}
}
var html_str = new HtmlString(markers_str);
}
@html_str
}
}
console.log(ViewBag.getAlamatVehicle);
</script>
结果:
var ViewBag = {
IsDesigner: ("False").toLowerCase() === 'true',
IsAdmin: ("True").toLowerCase() === 'true',
EmptyGuid: "00000000-0000-0000-0000-000000000000",
Advertisers_ID: "7e49def2-3887-4149-b419-5f1f51d4ec58",
Primary_Category: "Construction Services",
Primary_Category_ID: "ca9381c7-0379-4a72-80df-270287954164",
Advertiser_Name: "Dolphin Ayeyarwady Pile Construction Co., Ltd.",
Advertiser_NameMM: "",
BookTypeName: "YD",
getAlamatVehicle: {
"v1": "Bali", "v2": "Jakarta", "v3": "Bandung"
}
}
安慰:
Object {v1: "Bali", v2: "Jakarta", v3: "Bandung"}
以下是您可以如何实现该功能的方法:
function GetViewBagDictionary(id) {
if (ViewBag.getAlamatVehicle.hasOwnProperty(id))
return ViewBag.getAlamatVehicle[id];
return "not found";
}
console.log(GetViewBagDictionary("v2"));
安慰:
Jakarta
测试:
console.log(GetViewBagDictionary("v4"));
安慰:
not found
请尝试在JavaScript中foreach循环。
function GetViewBagDictionary() {
@foreach (var item in ViewBag.getAlamatVehicle)
{
var key = item.Key;
var Value = item.Value;
}
}
链接地址: http://www.djcxy.com/p/30403.html
上一篇: asp.net mvc display ViewBag dictionary to javascript
下一篇: How do I get key/value of a Dictionnary with an Iterator?