本章主要和大家分享下在ASP.NET MVC中我們的Action如何向視圖傳遞匿名類型的值。 ...
在使用ASP.NET MVC過程中想必大家都有遇到過一個問題就是我們的Action如何向視圖傳遞匿名類型的值呢,如果不做特殊處理則無法實現。
接下來我們來看一個示例:
在我們的控制中:
using System.Collections.Generic; using System.Web.Mvc; namespace TianYa.DotNetShare.MvcDemo.Controllers { public class DemoController : Controller { // GET: Demo public ActionResult Index() { var listStu = new List<dynamic> { new { SNo="1000", Name = "張三", Sex = "男", Age =20 }, new { SNo="1001", Name = "李四", Sex = "男", Age =21 } }; var stu = new { SNo = "1002", Name = "錢七七", Sex = "女", Age = 20 }; ViewBag.stu = stu; ViewBag.listStu = listStu; return View(); } } }
在我們的視圖中:
@{ Layout = null; } <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width" /> <title>Index</title> </head> <body> <div> @foreach (var item in ViewBag.listStu) { <p>學號:@(item.SNo),姓名:@(item.Name),性別:@(item.Sex),年齡:@(item.Age)。</p> } <p> 學號:@(ViewBag.stu.SNo),姓名:@(ViewBag.stu.Name),性別:@(ViewBag.stu.Sex),年齡:@(ViewBag.stu.Age)。 </p> </div> </body> </html>
然後將網站部署到我們的IIS上面,接下來來訪問一下我們的/demo/index
可以發現報錯了,說明傳值失敗了,那麼接下來我們來簡單介紹下如何解決這個問題。
首先添加一個擴展方法幫助類:
using System; using System.Collections.Generic; using System.ComponentModel; using System.Dynamic; using System.Linq; using System.Xml; namespace TianYa.DotNetShare.CommTool { /// <summary> /// 擴展方法 /// </summary> public static class ExtentMethod { #region 匿名對象處理 #region 將對象[主要是匿名對象]轉換為dynamic /// <summary> /// 將對象[主要是匿名對象]轉換為dynamic /// </summary> public static dynamic ToDynamic(this object value) { IDictionary<string, object> expando = new ExpandoObject(); var type = value.GetType(); var properties = TypeDescriptor.GetProperties(type); foreach (PropertyDescriptor property in properties) { var val = property.GetValue(value); if (property.PropertyType.FullName.StartsWith("<>f__AnonymousType")) { dynamic dval = val.ToDynamic(); expando.Add(property.Name, dval); } else { expando.Add(property.Name, val); } } return expando as ExpandoObject; } #endregion #region 將對象[主要是匿名對象]轉換為List<dynamic> /// <summary> /// 將對象[主要是匿名對象]轉換為List<dynamic> /// </summary> public static List<dynamic> ToDynamicList(this IEnumerable<dynamic> values) { var list = new List<dynamic>(); if (values != null) { if (values.Any()) { list.AddRange(values.Select(v => ((object)v).ToDynamic())); } } return list; } #endregion #region 將匿名對象集合轉換為XML /// <summary> /// 將匿名對象集合轉換為XML /// </summary> public static XmlDocument ListObjertToXML(this IEnumerable<dynamic> values) { var xmlDoc = new XmlDocument(); var xmlElem = xmlDoc.CreateElement("DocumentElement"); xmlDoc.AppendChild(xmlElem); if (values != null) { if (values.Any()) { var node = xmlDoc.SelectSingleNode("DocumentElement"); foreach (var item in values) { var xmlRow = xmlDoc.CreateElement("Row"); ObjectToXML(item, xmlDoc, xmlRow); node.AppendChild(xmlRow); } } } return xmlDoc; } #endregion #region 將匿名對象填充XML節點 /// <summary> /// 將匿名對象填充XML節點 /// </summary> private static void ObjectToXML(object value, XmlDocument xmlDoc, XmlElement xmlRow) { IDictionary<string, object> expando = new ExpandoObject(); var type = value.GetType(); var properties = TypeDescriptor.GetProperties(type); foreach (PropertyDescriptor property in properties) { var val = property.GetValue(value); xmlRow.CloneNode(false); var xmlTemp = xmlDoc.CreateElement(property.Name); XmlText xmlText; if (property.PropertyType.FullName.StartsWith("<>f__AnonymousType")) { dynamic dval = val.ToDynamic(); xmlText = xmlDoc.CreateTextNode(dval.ObjectToString()); } else { xmlText = xmlDoc.CreateTextNode(val.ToString()); } xmlTemp.AppendChild(xmlText); xmlRow.AppendChild(xmlTemp); } } #endregion #endregion } }
然後對我們的控制器做一些調整,增加調用我們的擴展方法:
using System.Collections.Generic; using System.Web.Mvc; using TianYa.DotNetShare.CommTool; namespace TianYa.DotNetShare.MvcDemo.Controllers { public class DemoController : Controller { // GET: Demo public ActionResult Index() { var listStu = new List<dynamic> { new { SNo="1000", Name = "張三", Sex = "男", Age =20 }, new { SNo="1001", Name = "李四", Sex = "男", Age =21 } }; var stu = new { SNo = "1002", Name = "錢七七", Sex = "女", Age = 20 }; ViewBag.stu = stu.ToDynamic(); ViewBag.listStu = listStu.ToDynamicList(); return View(); } } }
處理完後再來訪問一下我們的/demo/index
可以看出正常顯示了,說明我們的傳值成功了。
至此,本章就介紹完了,如果你覺得這篇文章對你有所幫助請記得點贊哦,謝謝!!!
demo源碼:
鏈接:https://pan.baidu.com/s/1_EXtKKYBYBFpBf5aDT4ASw 提取碼:atem
版權聲明:如有雷同純屬巧合,如有侵權請及時聯繫本人修改,謝謝!!!