使用ViewDataDictionary实例传递对象?

时间:2013-09-16 13:17:02

标签: asp.net-mvc asp.net-mvc-4

我有一个小疑问,就是下面的方法将对象添加到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();
}

2 个答案:

答案 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>