如果类型是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 代替直接的 { }。

posted @ 2014-03-11 16:05  陆敏技  阅读(459)  评论(0编辑  收藏  举报
Web Counter
Coupon for Contacts