我有一个小疑问,就是下面的方法将对象添加到ViewData Model属性中。
public ActionResult StronglyTypedView()
{
var obj = new MvcRouting.Models.Student();
obj.age = 24;
obj.name = "prab";
ViewData.Model = obj;
return View();
}
ViewData property
返回ViewDataDictionary
中的类型。所以我创建了ViewDataDictionary
的实例并将对象分配给了Model
属性。但是它不起作用,如何解决这个问题?
public ActionResult StronglyTypedView()
{
var obj = new MvcRouting.Models.Student();
obj.age = 24;
obj.name = "prab";
var DicObj = new ViewDataDictionary();
DicObj.Model = obj;
return View();
}
答案 0 :(得分:2)
我不建议这样做,但您可以直接从动作返回ViewResult
:
public ActionResult StronglyTypedView()
{
var obj = new MvcRouting.Models.Student();
obj.age = 24;
obj.name = "prab";
var DicObj = new ViewDataDictionary();
DicObj.Model = obj;
return new ViewResult
{
ViewData = DicObj
};
}
答案 1 :(得分:0)
按以下方式更改您的操作:
public ActionResult StronglyTypedView()
{
var obj = new MvcRouting.Models.Student();
obj.age = 24;
obj.name = "prab";
ViewData["Model"] = obj;
return View();
}
并且在您看来,这样的事情:
<div>@((MvcRouting.Models.Student)ViewData["Model"].name)</div>