Search code examples
asp.netasp.net-mvcasp.net-core-mvcasp.net-core-tag-helpers

ASP.NET Core - TagHelper, Partial Views and property name conflict


In an ASP.NET Core MVC project, say I have two partial views _viewA and _viewB and two associated models ModelA and ModelB.

And say both ModelA and ModelB have a property called MyProperty. Then in both _viewA and _viewB I use asp-for="MyProperty".

My issue is that my page ends up with two html elements with the same id.
How can I avoid that?

Note that I don't want to rename MyProperty as my models should not care about UI constraints.


Solution

  • Tks to @stephen-muecke as well as this post I've solved the problem with HtmlFieldPrefix. Here is an extension method that works with .Net Core to be used in @html.PartialFor("_viewA", "viewAPrefix"). Then all ids and names within the partial view are prefixed (even without using asp-for).

    public static IHtmlContent PartialFor(this IHtmlHelper helper, string partialViewName, string prefix)
    {
        var viewData = new ViewDataDictionary(helper.ViewData);
        var htmlPrefix = viewData.TemplateInfo.HtmlFieldPrefix;
        viewData.TemplateInfo.HtmlFieldPrefix += !Equals(htmlPrefix, string.Empty) ? $".{prefix}" : prefix;
        return helper.Partial(partialViewName, viewData);
    }