getting the values from a nested complex object that is passed to a partial view

后端 未结 4 984
感动是毒
感动是毒 2020-11-22 12:32

I have a ViewModel that has a complex object as one of its members. The complex object has 4 properties (all strings). I\'m trying to create a re-usable partial view where

4条回答
  •  梦谈多话
    2020-11-22 12:46

    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 will become 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(this HtmlHelper helper, Expression> 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")
    

提交回复
热议问题