Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
233 views
in Technique[技术] by (71.8m points)

c# - 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.

question from:https://stackoverflow.com/questions/15148103/mvc-4-how-do-i-pass-model-data-to-a-partial-view

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...