在 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 代替直接的 { }。