In the process of using ASP.NET MVC, we must all have encountered a problem: how can our Action pass anonymous type values to the view, which can not be achieved without special processing.
Next, let's look at an example:
In our control:
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 = "Zhang San", Sex = "male", Age =20 }, new { SNo="1001", Name = "Li Si", Sex = "male", Age =21 } }; var stu = new { SNo = "1002", Name = "Qian Qi Qi", Sex = "female", Age = 20 }; ViewBag.stu = stu; ViewBag.listStu = listStu; return View(); } } }
In our 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>Student ID:@(item.SNo),Full name:@(item.Name),Gender:@(item.Sex),Age:@(item.Age). </p> } <p> Student ID:@(ViewBag.stu.SNo),Full name:@(ViewBag.stu.Name),Gender:@(ViewBag.stu.Sex),Age:@(ViewBag.stu.Age). </p> </div> </body> </html>
Then deploy the website to our IIS, and then visit our / demo/index
It can be found that the report is wrong, indicating that the value transfer failed, then let's briefly introduce how to solve this problem.
First, add an extended method help class:
using System; using System.Collections.Generic; using System.ComponentModel; using System.Dynamic; using System.Linq; using System.Xml; namespace TianYa.DotNetShare.CommTool { /// <summary> /// Extension method /// </summary> public static class ExtentMethod { #region Anonymous Object Processing #region Will object[Primarily anonymous objects]Convert to dynamic /// <summary> /// Will object[Primarily anonymous objects]Convert to 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 Will object[Primarily anonymous objects]Convert to List<dynamic> /// <summary> /// Will object[Primarily anonymous objects]Convert to 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 Converting an anonymous collection of objects to XML /// <summary> /// Converting an anonymous collection of objects to 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 Fill in anonymous objects XML node /// <summary> /// Fill in anonymous objects XML node /// </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 } }
Then we make some adjustments to our controllers and add calls to our extension methods:
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 = "Zhang San", Sex = "male", Age =20 }, new { SNo="1001", Name = "Li Si", Sex = "male", Age =21 } }; var stu = new { SNo = "1002", Name = "Qian Qi Qi", Sex = "female", Age = 20 }; ViewBag.stu = stu.ToDynamic(); ViewBag.listStu = listStu.ToDynamicList(); return View(); } } }
Visit our / demo/index again after processing.
It can be seen that the normal display shows that our value transfer has been successful.
So far, this chapter is finished. If you think this article is helpful to you, please remember to praise it. Thank you!!!
demo source code:
Link: https://pan.baidu.com/s/1_EXtKYBYBFpBf5aDT4ASw Extraction code: atem
Copyright Statement: If similarities and similarities are pure coincidence, if there are infringements, please contact me to amend them in time, thank you!!!