RollerCosta
RollerCosta

Reputation: 5216

how to access object in view (asp.net mvc)?

If Controller action passing object of some ViewModel say("otherViewModeObj") to a view Which is Strongly typed to other ViewMOdel say("mainViewModel") then how rendered view access that object directly and also use that object to pass some partial View.

Updated

public class MainViewModel 
     { 
        prop1{}
        prop2{}
     } 



public class SubViewModel 
{ 

public list<SubViewModel> obj{ get; set; } 

}



Action

  Public ActionResut action()
    {
     return View(SubViewModelObj)//But View is Strongly typed to MainViewModel 
    }



Then how can i access that obj (of SubViewModelObj) inn that view??

Upvotes: 0

Views: 1822

Answers (2)

user191966
user191966

Reputation:

You cannot do that. You have a few options:

  1. Have SubViewModel inherit from MainViewModel (I actually haven't tried this, but it should work). Then, this should work return View(SubViewModelObj) but you'll have to cast the model object to SubViewModel within the view. I don't like this approach at all. I said it to be objective.
  2. Pass data to view via ViewData or ViewBag properties of the controller: this.ViewData["your_object_id_or_name"] = SubViewModelObj; Then you can use is within the view as: var myobj = (SubViewModel)this.ViewData["your_object_id_or_name"];
  3. Refactor those two model classes into one. Obviously, some properties of that model are used as optional within the view, so there's nothing wrong with having them set to null (or other default values) and ignore them.

Upvotes: 0

Per Kastman
Per Kastman

Reputation: 4504

I'm not sure if I understand your question totally, but what you could do is to have the other viewModel as a property in the main view model.

public class SubViewModel
{

}

public class MainViewModel
{
  //MainViewModel properties

  public SubViewModel SubViewModelData { get; set; }

}

In view:

@Html.Partial("_SomePartialView", Model.SubViewModelData)

Upvotes: 1

Related Questions