Created
June 27, 2012 15:04
-
-
Save benfoster/3004655 to your computer and use it in GitHub Desktop.
Composite Views in ASP.NET MVC
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public interface IWidget | |
{ | |
string Title { get; } | |
IHtmlString Render(HtmlHelper htmlHelper); | |
} | |
public class LatestTweetsWidget : IWidget | |
{ | |
public string Title { get { return "Latest Tweets"; } } | |
public string Handle { get; set; } | |
public IHtmlString Render(HtmlHelper htmlHelper) | |
{ | |
return htmlHelper.Partial("Tweets", this); | |
} | |
} | |
public class WidgetPage | |
{ | |
public List<IWidget> Widgets { get; set; } | |
public WidgetPage() | |
{ | |
Widgets = new List<IWidget>(); | |
} | |
} | |
public class WidgetsController : Controller | |
{ | |
public ActionResult Page(string id) | |
{ | |
// assume loading page from somewhere | |
var page = new WidgetPage(); | |
// assume loading and building widgets (somehow) | |
page.Widgets.Add(new LatestTweetsWidget { Handle = "benfosterdev" }); | |
return View(page); | |
} | |
} | |
// View: | |
@model WidgetPage | |
@foreach (var widget in Model.Widgets) { | |
<div class="widget"> | |
<h2>@widget.Title</h2> | |
@widget.Render(Html) | |
</div> | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment