Created
June 22, 2016 14:24
-
-
Save hidegh/9c6adb13d70d96a60833e92593c6606a to your computer and use it in GitHub Desktop.
This file contains 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 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