Skip to content

Instantly share code, notes, and snippets.

@joeriks
Last active March 8, 2021 08:14
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save joeriks/b9e6336b04b48e99b9cf to your computer and use it in GitHub Desktop.
Save joeriks/b9e6336b04b48e99b9cf to your computer and use it in GitHub Desktop.
PartialFor - resolve name of partial from type name or from UIHint (like DisplayFor)
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>
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 templateName = "")
{
var model = expression.Compile()(htmlHelper.ViewData.Model);
// if model is null return blank string
if (model == null) return new MvcHtmlString("");
if (templateName == "")
{
// try resolve template name from property attribute UIHint (e.g. [UIHint("Foo")])
var nm = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);
templateName = nm.TemplateHint;
// try resolve template name from property type name
if (templateName == null)
templateName = model.GetType().Name;
}
return htmlHelper.Partial(templateName, model);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment