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

 

版权声明:如有雷同纯属巧合,如有侵权请及时联系本人修改,谢谢!!!

posted @ 2019-08-13 21:25  谢友海  阅读(935)  评论(0编辑  收藏  举报