Skip to content

Instantly share code, notes, and snippets.

@greystate
Forked from joeriks/ArticlePageViewModel.cs
Last active August 29, 2015 14:05
Show Gist options
  • Save greystate/53df4b4d68826589e036 to your computer and use it in GitHub Desktop.
Save greystate/53df4b4d68826589e036 to your computer and use it in GitHub Desktop.
public class CompanyViewModel {
// use partial view "StreetAddress.cshtml"
public StreetAddress MainAddress {get; set;}
// use partial view "CompactAddress.cshtml"
[UIHint("CompactAddress")]
public StreetAddress StoreAddress {get; set;}
}
@Html.RenderPartialFor(m=>m.MainAddress)
@Html.RenderPartialFor(m=>m.StoreAddress)
using System;
using System.Linq.Expressions;
using System.Web.Mvc;
using System.Web.Mvc.Html;
public static class RenderPartialForExtensions
{
public static MvcHtmlString RenderPartialFor<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