Question

MVC 3 with Razor question about partial views.

I have this :

@model MvcGroupie.Models.Message

@{
    ViewBag.Title = "Details";
}

<h2>Details</h2>

<fieldset>
    <legend>Message</legend>

    <div class="display-label">postCreator</div>
    <div class="display-field">@Model.postCreator</div>

    <div class="display-label">postDate</div>
    <div class="display-field">@String.Format("{0:g}", Model.postDate)</div>

    <div class="display-label">postSubject</div>
    <div class="display-field">@Model.postSubject</div>

    <div class="display-label">postBody</div>
    <div class="display-field">@Model.postBody</div>
</fieldset>

    @Html.Partial("~/Views/Shared/replyPartial.cshtml")
<p>
    @if(Model.postCreator == User.Identity.Name) {@Html.ActionLink("Edit", "Edit", new { id=Model.postID } + " | ")} 
    @Html.ActionLink("Reply", "Reply", new { id=Model.postID }) |                                                                
    @Html.ActionLink("Back to List", "Index")
</p>

For a very simple post and reply MVC app im playing with for learning. I cant get a partial to display for replies :/

If i add the partial i get 'MvcGroupie.Models.Message', but this dictionary requires a model item of type 'MvcGroupie.Models.Reply'. Ok, so you cant ever use diff models on the same page? The first line starts with @model MvcGroupie.Models.Message so i can access the model.postSubject and the like. But if i want to add the replies and have people able to reply from the same page it doesnt allow it, they would fall under @model MvcGroupie.Models.Reply...

Curious how to get around this... I tried @Html.Partial("~/Views/Shared/replyPartial.cshtml", Model.Reply) but it doesnt recognize Model.Reply ....

Serious roadblock in my way of learning any help?

Was it helpful?

Solution

When you make the call to render a partial view that takes a different model you need to pass the model to that view. The default behavior is that the partial view will use the same model as the view that called it, but that won't work in your case because the models are different.

Try this:

@Html.RenderPartial("~/Views/Shared/replyPartial.cshtml", Model.Replies)

I'm assuming your Message object has a Replies property. Don't forget to do a null check in your partial view in case the message doesn't have any replies.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top