我在Controller中从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>
两者都不起作用。那怎么办?
注意:我不希望使用具有硬编码属性名称的强类型对象。
感谢。