getting the values from a nested complex object that is passed to a partial view
You can pass the prefix to the partial using
@Html.Partial("MyPartialView", Model.ComplexModel,
new ViewDataDictionary { TemplateInfo = new TemplateInfo { HtmlFieldPrefix = "ComplexModel" }})
which will perpend the prefix to you controls name
attribute so that <input name="Name" ../>
will become <input name="ComplexModel.Name" ../>
and correctly bind to typeof MyViewModel
on post back
Edit
To make it a little easier, you can encapsulate this in a html helper
public static MvcHtmlString PartialFor<TModel, TProperty>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TProperty>> expression, string partialViewName)
{
string name = ExpressionHelper.GetExpressionText(expression);
object model = ModelMetadata.FromLambdaExpression(expression, helper.ViewData).Model;
var viewData = new ViewDataDictionary(helper.ViewData)
{
TemplateInfo = new System.Web.Mvc.TemplateInfo
{
HtmlFieldPrefix = string.IsNullOrEmpty(helper.ViewData.TemplateInfo.HtmlFieldPrefix) ?
name : $"{helper.ViewData.TemplateInfo.HtmlFieldPrefix}.{name}"
}
};
return helper.Partial(partialViewName, model, viewData);
}
and use it as
@Html.PartialFor(m => m.ComplexModel, "MyPartialView")
If you use tag helpers, the partial
tag helper accepts a for
attribute, which does what you expect.
<partial name="MyPartialView" for="ComplexModel" />
Using the for
attribute, rather than the typical model
attribute, will cause all of the form fields within the partial to be named with the ComplexModel.
prefix.