0

我有一个小疑问,即以下方法将对象添加到 ViewData 模型属性。

  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();
}
4

2 回答 2

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
               };
}
于 2013-09-16T13:30:28.007 回答
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>
于 2013-09-16T13:30:06.183 回答