Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC 4 - how do I pass model data to a partial view?

I'm building a profile page that will have a number of sections that relate to a particular model (Tenant) - AboutMe, MyPreferences - those kind of things. Each one of those sections is going to be a partial view, to allow for partial page updates using AJAX.

When I click on an ActionResult in the TenantController I'm able to create a strongly typed view and the model data is passed to the view fine. I can't achieve this with partial views.

I've created a partial view _TenantDetailsPartial:

@model LetLord.Models.Tenant <div class="row-fluid">     @Html.LabelFor(x => x.UserName) // this displays UserName when not in IF     @Html.DisplayFor(x => x.UserName) // this displays nothing </div> 

I then have a view MyProfile that will render mentioned partial views:

@model LetLord.Models.Tenant <div class="row-fluid">     <div class="span4 well-border">          @Html.Partial("~/Views/Tenants/_TenantDetailsPartial.cshtml",           new ViewDataDictionary<LetLord.Models.Tenant>())     </div> </div> 

If I wrap the code inside the DIV in _TenantDetailsPartial inside @if(model != null){} nothing gets displayed on the page, so I'm guessing there is an empty model being passed to the view.

How come when I create a strongly typed view from an ActionResult the user in the 'session' gets passed to the view? How can pass the user in the 'session' to a partial view that is not created from an ActionResult? If I'm missing something about the concept, please explain.

like image 871
MattSull Avatar asked Mar 01 '13 00:03

MattSull


People also ask

How do you pass value from model to view?

The other way of passing the data from Controller to View can be by passing an object of the model class to the View. Erase the code of ViewData and pass the object of model class in return view. Import the binding object of model class at the top of Index View and access the properties by @Model.


1 Answers

You're not actually passing the model to the Partial, you're passing a new ViewDataDictionary<LetLord.Models.Tenant>(). Try this:

@model LetLord.Models.Tenant <div class="row-fluid">     <div class="span4 well-border">          @Html.Partial("~/Views/Tenants/_TenantDetailsPartial.cshtml", Model)     </div> </div> 
like image 91
Daniel Imms Avatar answered Oct 06 '22 00:10

Daniel Imms