我在控制器中有一个从 ExpandoObject 获取的 ViewData 值,如下所示:
public ActionResult CountryData()
{
string json = "{\"Countries\":[{\"CountryId\":1,\"Country\":\"USA\",\"Description\":\"North America\"},{\"CountryId\":2,\"Country\":\"Russia\",\"Description\":\"Europe\"},{\"CountryId\":3,\"Country\":\"Argentina\",\"Description\":\"South America\"}]}";
dynamic values = deserializeToDictionary(json);
ViewData[key2] = values[key2]; //the key is "Countries"
return View();
}
private Dictionary<string, object> deserializeToDictionary(string JsonString)
{
dynamic dataObj = new ExpandoObject();
var values = dataObj as IDictionary<string, object>;
values = JsonConvert.DeserializeObject<ExpandoObject>(JsonString);
Dictionary<string, object> values2 = new Dictionary<string, object>();
foreach (KeyValuePair<string, object> d in values)
{
if (d.Value.GetType().FullName.Contains("Newtonsoft.Json.Linq.JObject"))
{
values2.Add(d.Key, deserializeToDictionary(d.Value.ToString()));
}
else
{
values2.Add(d.Key, d.Value);
}
}
return values2;
}
注意:从SO中提取的代码。
我尝试了几种在模板中引用它的方法,但似乎无法使其工作。
(a) 我尝试了正常的字典查找:
<select name="Countries" >
<option value=""></option>
$Countries:{Country
<option title="$Country["Capital"]$" $if(Country["Selected"]="")$ selected="selected" $endif$ value="$Country["CountryId"]$">$Country["Name"]$</option>
}$
</select>
和
<select name="Countries" >
<option value=""></option>
$Countries:{Country
<option title="$Country[2]$" $if(Country[3]="")$ selected="selected" $endif$ value="$Country[0]$">$Country[1]$</option>
}$
</select>
(b) 也尝试了引用强类型值/数据传输对象的正常方法
<select name="Countries" >
<option value=""></option>
$Countries:{Country
<option title="$Country.Capital$" $if(Country.Selected="")$ selected="selected" $endif$ value="$Country.CountryId$">$Country.Name$</option>
}$
</select>
两者都没有工作。那么它是如何完成的呢?
注意:我不希望使用带有硬编码属性名称的强类型对象。
谢谢。