MattSull MattSull - 3 months ago 14
C# Question

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.

Answer

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>
Comments