Monday, July 2, 2012

Razor - Partial Views


HTML/C# code in a file for reuse in other views. Helps avoid duplication of markup.

Prefix the partial view with an underscore as a convention.

Can still use the strongly typed view.

If you have already generated tags as normal view, can leave scaffold template empty and copy and paste the tags in the partial view.

[x] Create as a partial view (=> does not set the title)

@model xxx.Models.xxx  // strongly-typed
Razor code here that references the Model directly
<div class=”review”>
  <h4>@Model.Restaurant.Name</h4>
...

To render partial view in a normal View.

@foreach (var item in Model)
{
// Render portion of the model in a specific view
 @Html.Partial(“_partialviewName”, item) // item becomes the Model for the partial view
}

If partial view is placed in Views folder, it is only available to views in that folder.

If in Shared folder, can use it anywhere in the app.

Another use of partial view... delegate work to some other controller.

Rendering partial view that does not really have a model associated with it. Executed for different views; those views will be using different models.

For example, say we want to place output of some (sub-)controller in an area of the main view.

// 1) create a controller action that returns the partial view
public ActionResult BestReview()
{
 var model = _db.Reviews.FindTheBest();
 return PartialView(“_Review”, model);
}

// 2) Invoke the sub-co0ntr
<div id=”main>
 @RenderBody()
 <div id=”footer”>

// we may want to show this information on every page
 @Html.Action(“BestReview”, “Reviews”)
// does not require any specify type of model; the controller generates everything;
//  it still takes advantage of strongly-typed view

// this was specified in the View for copyright; separate from BestReview
 @RenderSection(“Footer”, false)
 </div>
</div>
</div>

To make the following not accessible from Browser:
[ChildActionOnly]
public ActionResult BestReview()
{
 var model = _db.Reviews.FindTheBest();
 return PartialView(“_Review”, model);
}