Prabhakaran Parthipan
Prabhakaran Parthipan

Reputation: 4273

Passing object by using ViewDataDictionary instance?

I got one small doubt,that is the following method adds object to ViewData Model property.

  public ActionResult StronglyTypedView()
  {
            var obj = new MvcRouting.Models.Student();
            obj.age = 24;
            obj.name = "prab";
            ViewData.Model = obj;           
            return View();
  }

ViewData property return type in ViewDataDictionary.So i created instance of ViewDataDictionary and assigned object to Model property.But its not working,how to solve this?

public ActionResult StronglyTypedView()
{
   var obj = new MvcRouting.Models.Student();
   obj.age = 24;
   obj.name = "prab";
   var DicObj = new ViewDataDictionary();
   DicObj.Model = obj;
   return View();
}

Upvotes: 0

Views: 311

Answers (2)

Zabavsky
Zabavsky

Reputation: 13640

I wouldn't suggest doing so, but you can return the ViewResult directly from the action:

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
               };
}

Upvotes: 2

Amin Saqi
Amin Saqi

Reputation: 18977

Change your action like the following:

public ActionResult StronglyTypedView()
{
        var obj = new MvcRouting.Models.Student();
        obj.age = 24;
        obj.name = "prab";
        ViewData["Model"] = obj;           
        return View();
}

and in your view, something like this:

<div>@((MvcRouting.Models.Student)ViewData["Model"].name)</div>

Upvotes: 0

Related Questions