Send data to a partial view in Umbraco 7

Sometimes you want a partial view in Umbraco with a custom model. You can achieve that using a custom model and the UmbracoViewPage like this

@* SomePartialView: *@
@inherits Umbraco.Web.Mvc.UmbracoViewPage<MyViewModel>
@Model.MyData
@* the view: *@
@Html.Partial("SomePartialView", new MyViewModel{MyData="foo"})

But how to be able to use the regular RenderModel published content model aswell?

Alternative 1

@{
  ViewData["MyData"]="foo";
}
@{
  @ViewData["MyData"];
}

Alternative 2

Include it as a property in your model. Or subclass the viewmodel from the RenderModel (ref http://our.umbraco.org/forum/templating/templates-and-document-types/38311-Using-RenderMvcController?p=2)

public class MyViewModel : Umbraco.Web.Models.RenderModel
{
    public BaseModel(IPublishedContent content)
        : base(content)
    {

    }
}

Alternative 3

Use the ViewDataDictionary:

@Html.Partial("SomePartialView", new ViewDataDictionary { { "MyData", "The value" } })
@* the view *@
@Model.Content...
@ViewData["MyData"]

Also – sometimes you want to send documents to the partial view, then simply use the IPublishedContent

@inherits Umbraco.Web.Mvc.UmbracoViewPage<IEnumerable<IPublishedContent>>;
@foreach(var doc in Model){
...
}
@Html.Partial("SomeKindOfDocumentList", Model.Content.Children())

Re-use the same view for another set of children:

@Html.Partial("SomeKindOfDocumentList", Model.Content.AncestorOrSelf(3).Children())
Advertisements

One thought on “Send data to a partial view in Umbraco 7

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s