zoukankan      html  css  js  c++  java
  • 如果类型是dynamic的且其属性也是dynamic的

    在 MVC 中,如果尝试如下的编码:

    public ActionResult TeacherInfo(string courseId)
    {
        var x = LearningBll.GetTeacherInfo(courseId);
        if (x == null)
        {
            x = new
            {
                Id = "1",
                Name = "不详",
                Introduce = "无"
            };
        }
        return View(x);
    }

    或:

    public ActionResult TeacherInfo(string courseId)
    {
        var x = LearningBll.GetTeacherInfo(courseId);
        if (x == null)
        {
            x = new
            {
                Id = "1",
                Name = "不详",
                Introduce = "无"
            };
        }

        ViewBag.Teacher = x;
    }

    那么,前台在调用 Model.Id 或者 ViewBag.Teacher.Id 的时候,会直接报错,一种回旋的做法是:

    public ActionResult TeacherInfo(string courseId)
    {
        var x = LearningBll.GetTeacherInfo(courseId);
        if (x == null)
        {
            x = new ExpandoObject();
            x.Id = "1";
            x.Name = "不详";
            x.Introduce = "无";
        }

        //ViewBag.Teacher = x;
        return View(x);
    }

    即:使用 ExpandoObject 代替直接的 { }。

  • 相关阅读:
    C 语言实例
    C 语言实例
    C 语言实例
    C 语言实例
    C 语言实例
    C 语言实例
    C 语言实例
    C 语言实例
    YQCB冲刺第二周第二天
    YQCB冲刺第二周第一天
  • 原文地址:https://www.cnblogs.com/luminji/p/3594186.html
Copyright © 2011-2022 走看看