Skip to content

Instantly share code, notes, and snippets.

@hidegh
Created June 22, 2016 14:24
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 hidegh/9c6adb13d70d96a60833e92593c6606a to your computer and use it in GitHub Desktop.
Save hidegh/9c6adb13d70d96a60833e92593c6606a to your computer and use it in GitHub Desktop.
public static MvcHtmlString PartialFor<TModel, TProperty>(
this HtmlHelper<TModel> helper,
System.Linq.Expressions.Expression<Func<TModel, TProperty>> expression,
string partialViewName,
Dictionary<string, object> additionalViewData = null
)
{
// Get model value from expression
string name = ExpressionHelper.GetExpressionText(expression);
var modelMetadata = ModelMetadata.FromLambdaExpression(expression, helper.ViewData);
var model = modelMetadata.Model;
Type modelType = modelMetadata.ModelType;
// Apply TemplateInfo to have hierarchical input naming convention
var viewData = new ViewDataDictionary(helper.ViewData)
{
TemplateInfo = new TemplateInfo
{
HtmlFieldPrefix = string.IsNullOrWhiteSpace(helper.ViewData.TemplateInfo.HtmlFieldPrefix)
? name
: helper.ViewData.TemplateInfo.HtmlFieldPrefix + "." + name
}
};
// Copy additional key/values to the ViewData...
additionalViewData = additionalViewData ?? new Dictionary<string, object>();
foreach (var d in additionalViewData)
{
viewData[d.Key] = d.Value;
}
// Clear the parent model from the partial view's ViewDataDictionary
viewData.Model = null;
// Get PartialView MvcHtmlString...by passing in the new (sub-) model
return helper.Partial(partialViewName, model, viewData);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment