Click here to Skip to main content
15,881,380 members
Articles / DevOps
Tip/Trick

Bind PartialView / RenderPartialView to Model Child Objects Automatically

Rate me:
Please Sign up or sign in to vote.
5.00/5 (1 vote)
23 Aug 2017CPOL 8.3K   5   3
Automatically bind MVC HTML RenderPartial and Partial view pages to your model's child objects without having to use HTMLFieldPrefix.

Introduction

Tired of fighting with PartialViews that won't bind to your model? This simple set of functions handles automatically fixing the HTML prefix and allows PartialPages to bind without any further effort.

Using the Code

Simply add the following class into your solution and then instead of using Html.Partial or Html.RenderPartial, call it like the functions below:

Usage:

C#
@Html.RenderPartialFixChildPrefix("_PartialView", model.ChildObject)

or:

C#
@Html.PartialFixChildPrefix("_PartialView", model.ChildObject)

Extension Class:

C#
 public static class PartialExtensions
    {
        public static void RenderPartialFixChildPrefix
        (this HtmlHelper htmlHelper, string partialViewName, 
         object model, ViewDataDictionary viewData = null)
        {
            if (model == null)
            {
                throw new Exception("Null models cannot be processed correctly. 
                                          Initialize empty object for create calls.");
            }

            using (StringWriter writer = new StringWriter(CultureInfo.CurrentCulture))
            {
                string oldPrefix = FixPartialPrefixIfNeeded(htmlHelper, model, ref viewData);
                htmlHelper.RenderPartial(partialViewName, model, viewData);
                viewData.TemplateInfo.HtmlFieldPrefix = oldPrefix;
            }
        }

        private static string FixPartialPrefixIfNeeded
        (HtmlHelper htmlHelper, object model, ref ViewDataDictionary viewData)
        {
            var oldPrefix = viewData == null ? "" : viewData.TemplateInfo.HtmlFieldPrefix;

            // Only change prefix if we're using a difference Model for the partial view
            if (model != htmlHelper.ViewData.Model)
            {
                var modelPropertyName = GetPropertyNameFromParentObj(htmlHelper.ViewData.Model, model);

                if (viewData == null)
                {
                    viewData = new ViewDataDictionary()
                    {
                        TemplateInfo = new TemplateInfo()
                    };
                }

                viewData.TemplateInfo.HtmlFieldPrefix = modelPropertyName;
            }
            return oldPrefix;
        }

        public static MvcHtmlString PartialFixChildPrefix
        (this HtmlHelper htmlHelper, string partialViewName, 
         object model, ViewDataDictionary viewData = null)
        {
            if (model == null)
            {
                throw new Exception("Null models cannot be processed correctly. 
                Initialize empty object for create calls.");
            }

            using (StringWriter writer = new StringWriter(CultureInfo.CurrentCulture))
            {
                string oldPrefix = FixPartialPrefixIfNeeded(htmlHelper, model, ref viewData);
                var result = htmlHelper.Partial(partialViewName, model, viewData);
                viewData.TemplateInfo.HtmlFieldPrefix = oldPrefix;
                return result;
            }
        }

        private static string GetPropertyNameFromParentObj(object parentObj, object objToFind)
        {
            var props = parentObj.GetType().GetProperties();

            foreach (var p in props)
            {
                string name = p.Name;
                var value = parentObj.GetType().GetProperty(p.Name).GetValue(parentObj, null);

                if (objToFind == value)
                {
                    return p.Name;
                }
            }

            return "";
        }
}

History

  • 8/22/2017 -- Initial posting - Allen Biehle c/o Vertical AIT (Vertical Automation and Information Technology, LLC)

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
CEO Vertical AIT (Vertical Automation & Information Te
United States United States
Software Architect and CEO of Vertical AIT.

We build intuitive Data Acquisition, Control, and Automation systems. We offer software for all of the Verticals of your business from firmware and data acquisition to web dashboards and reporting.

Education:
BS Computer Science + MBA
Texas A&M University

Comments and Discussions

 
PraiseAwesome Pin
Shamnani Kamlesh23-Aug-17 22:55
Shamnani Kamlesh23-Aug-17 22:55 
QuestionDoes it work with .net Core 2.0? Pin
Philipos Sakellaropoulos23-Aug-17 22:40
professionalPhilipos Sakellaropoulos23-Aug-17 22:40 
AnswerRe: Does it work with .net Core 2.0? Pin
Vertical AIT27-Sep-17 11:50
Vertical AIT27-Sep-17 11:50 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.