MVC 6 VNext how to set HtmlFieldPrefix?

后端 未结 2 1194
名媛妹妹
名媛妹妹 2021-01-18 21:08

My view is divided into partial views. Hence, at the time of submission my model isn\'t reconstructed correctly.

The page view displays employee data, where Employe

相关标签:
2条回答
  • 2021-01-18 21:38

    Here is the solution,

    namespace Website1.Extensions
    {
        public static class HtmlHelper
        {
            public static IHtmlContent Partial(this IHtmlHelper htmlHelper, string partialViewName, object model, string prefix)
            {
                var viewData = new ViewDataDictionary(htmlHelper.ViewData);
                var htmlPrefix = viewData.TemplateInfo.HtmlFieldPrefix;
                viewData.TemplateInfo.HtmlFieldPrefix += !Equals(htmlPrefix, string.Empty) ? $".{prefix}" : prefix;
                return htmlHelper.Partial(partialViewName, model, viewData);
            }
    
            public static Task<IHtmlContent> PartialAsync(this IHtmlHelper htmlHelper, string partialViewName, object model, string prefix)
            {
                var viewData = new ViewDataDictionary(htmlHelper.ViewData);
                var htmlPrefix = viewData.TemplateInfo.HtmlFieldPrefix;
                viewData.TemplateInfo.HtmlFieldPrefix += !Equals(htmlPrefix, string.Empty) ? $".{prefix}" : prefix;
                return htmlHelper.PartialAsync(partialViewName, model, viewData);
            }
        }
    }
    

    employee.cshtml

    @using Website1.Extensions;
    @model Employee
    @Html.Partial("_contactInfo", Model.ContactInfo, nameof(Model.ContactInfo))
    

    _contactInfo.cshtml

    @using Website1.Extensions;
    @model ContactInfo
    @Html.Partial("_phoneInfo", Model.PhoneInfo, nameof(Model.PhoneInfo))
    

    _phoneInfo.cshtml

    @model PhoneInfo
    <input asp-for="@Model.Contact1" />
    
    0 讨论(0)
  • 2021-01-18 21:40

    If you only need this once this would be the quick solution for the _contactInfo partial view

    employee.cshtml

       @{
            var viewData = new ViewDataDictionary(ViewData);
            viewData.TemplateInfo.HtmlFieldPrefix = "ContactInfo";
        }
    
        <partial name="_conctactInfo" model="Model.ContactInfo" view-data="@viewData"/>
    
    0 讨论(0)
提交回复
热议问题