Skip to content

Instantly share code, notes, and snippets.

@tboby
Forked from joeriks/ArticlePageViewModel.cs
Last active August 29, 2015 14:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tboby/e0e09c0d82121397b40c to your computer and use it in GitHub Desktop.
Save tboby/e0e09c0d82121397b40c to your computer and use it in GitHub Desktop.
PartialFor - resolve name of partial from type name or from UIHint (like DisplayFor)
using System;
using System.Linq.Expressions;
using System.Web.Mvc;
using System.Web.Mvc.Html;
public static class PartialForExtensions
{
public static MvcHtmlString PartialFor<T>(this HtmlHelper<T> htmlHelper, Expression<Func<T, object>> expression,
string partialViewName, ViewDataDictionary viewData)
{
var model = expression.Compile()(htmlHelper.ViewData.Model);
// if model is null return blank string
if (model == null) return new MvcHtmlString("");
if (partialViewName == null)
{
// try resolve template name from property attribute UIHint (e.g. [UIHint("Foo")])
var nm = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);
partialViewName = nm.TemplateHint;
// try resolve template name from property type name
if (partialViewName == null)
partialViewName = model.GetType().Name;
}
return htmlHelper.Partial(partialViewName, model, viewData);
}
public static MvcHtmlString PartialFor<T>(this HtmlHelper<T> htmlHelper, Expression<Func<T, object>> expression, string partialViewName)
{
return PartialFor<T>(htmlHelper, expression, partialViewName, htmlHelper.ViewData);
}
public static MvcHtmlString PartialFor<T>(this HtmlHelper<T> htmlHelper, Expression<Func<T, object>> expression, ViewDataDictionary viewData)
{
return PartialFor<T>(htmlHelper, expression, null, viewData);
}
}
public class ArticlePageViewModel {
// use partial view "TopMenuViewModel.cshtml"
public TopMenuViewModel TopMenu {get;set;}
// use partial view "WidgetsViewModel.cshtml"
public WidgetsViewModel Widgets {get;set;}
// use partial view "ExtraWidgets.cshtml"
[UIHint("ExtraWidgets")]
public WidgetsViewModel ExtraWidgets {get;set;}
}
@Html.PartialFor(m=>m.TopMenu)
<div class="right">
@Html.PartialFor(m=>m.Widgets)
</div>
<div class="extra">
@Html.PartialFor(m=>m.ExtraWidgets)
</div>
<div class="bottom">
@* using BottomWidgets.cshtml , this is not necessary as it equals the regular usage of html.partial *|
@Html.PartialFor(m=>m.ExtraWidgets, "BottomWidgets")
</div>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment