ExpandoObject作为ViewModel给view传值
Action
public ActionResult Index(string id) { dynamic d = new ExpandoObject(); d.id = id; d.name = "张三"; return View(d); }
View
@model dynamic <div> id=@Model.id name=@Model.name </div>
ExpandoObject转换为json
1、直接转换json,格式不是我们想要的
public ActionResult Test(string id) { dynamic d = new ExpandoObject(); d.id = id; d.name = "张三"; return Json(d, JsonRequestBehavior.AllowGet); //结果:[{"Key":"id","Value":"123"},{"Key":"name","Value":"张三"}] }
2、转换成IDictionary<string, object>,然后再转换为json就好了
public ActionResult Test(string id) { dynamic d = new ExpandoObject(); d.id = id; d.name = "张三"; var di = d as IDictionary<string, object>; di = di.ToDictionary(x => x.Key, x => x.Value); return Json(di, JsonRequestBehavior.AllowGet); }
//结果{"id":"123","name":"张三"}
3、另一种方法JSON.NET
public ActionResult Test(string id) { dynamic d = new ExpandoObject(); d.id = id; d.name = "张三"; var json = JsonConvert.SerializeObject(d); return Content(json, "application/json"); //结果正常:{"id":"123","name":"张三"}
}
扩展方法
/// <summary> /// 对象转成可以扩充的匿名对象 /// </summary> /// <param name="obj"></param> /// <returns></returns> public static dynamic ConvertToDynamic(object obj) { //知识点:ExpandoObject继承了IDictionary<String, Object>的接口 IDictionary<string, object> result = new ExpandoObject(); foreach (PropertyDescriptor pro in TypeDescriptor.GetProperties(obj.GetType())) { result.Add(pro.Name, pro.GetValue(obj)); } return result as ExpandoObject; /* //=============1、新增属性 //Product为一个class,默认只有一个属性Name Product p1 = new Product(); p1.Name = "商品名称"; dynamic result = ConvertToDynamic(p1); exProd.name1 = "我是新属性1"; exProd.name2 = "我是新属性2"; Response.Write(result.Name + "," + result.name1 + "," + result.name2); //=============2、删除属性 ((IDictionary<string, object>)result).Remove("Name2"); //=============3、枚举出已经存在的成员 foreach (var pro in (IDictionary<string, Object>)result) { Console.WriteLine(pro.Key+" "+pro.Value); } //============4、转换json var di = d as IDictionary<string, object>; di = di.ToDictionary(x => x.Key, x => x.Value); return Json(di, JsonRequestBehavior.AllowGet); */ }