1
votes

When I run the MVC request in a usual way the ASP attributes submerged within the HTML tags are correctly interpreted.

E.g.

This is what I have in the view,

        <ul class="nav navbar-nav">
            <li><a asp-controller="Home" asp-action="Index">Home</a></li>
            <li><a asp-controller="Home" asp-action="About">About</a></li>
            <li><a asp-controller="Home" asp-action="Contact">Contact</a></li>
        </ul>

This is what it translates to when it comes to the browser,

<ul class="nav navbar-nav">
      <li><a href="Home/Index">Home</a></li>
      <li><a href="/Home/About">About</a></li>
      <li><a href="/Home/Contact">Contact</a></li>
</ul>

Now, if I render the view through the following function,

    public string RenderPartialViewToString(string viewName, object model)
    {
        if (string.IsNullOrEmpty(viewName))
            viewName = ActionContext.ActionDescriptor.Name;

        ViewData.Model = model;

        using (StringWriter sw = new StringWriter())
        {
            var engine = Resolver.GetService(typeof(ICompositeViewEngine)) as ICompositeViewEngine;
            ViewEngineResult viewResult = engine.FindPartialView(ActionContext, viewName);

            ViewContext viewContext = new ViewContext(ActionContext, viewResult.View, 
            ViewData, TempData, sw, new HtmlHelperOptions());

            var t = viewResult.View.RenderAsync(viewContext);
            t.Wait();

            return sw.GetStringBuilder().ToString();
        }
    }

The attributes submerged within the anchor tags remain as-is, looks like they aren't interpreted by the view engine at all.

            <ul class="nav navbar-nav">
                <li><a asp-controller="Home" asp-action="Index">Home</a></li>
                <li><a asp-controller="Home" asp-action="About">About</a></li>
                <li><a asp-controller="Home" asp-action="Contact">Contact</a></li>
            </ul>
1
I imagine this is because these are tag helpers, not Razor.DavidG
Hi David, yes that's true but what's the resolution to make them work. I want to retrieve the flatten HTML for everything that is part of the view, including razor and tag helpers.Mukesh Bhojwani

1 Answers

1
votes

I tried your RenderPartialViewToString code and everything works fine for me. My guess that when you are using RenderPartialViewToString you put your view outside from standart View folder. So please try next code

@addTagHelper "*, Microsoft.AspNet.Mvc.TagHelpers"   

<ul class="nav navbar-nav">
    <li><a asp-controller="Home" asp-action="Index">Home</a></li>
    <li><a asp-controller="Home" asp-action="About">About</a></li>
    <li><a asp-controller="Home" asp-action="Contact">Contact</a></li>
</ul>

So if I am right and everything works fine after that you could try add _ViewImports.cshtml file into that folder and write @addTagHelper "*, Microsoft.AspNet.Mvc.TagHelpers" there so all view in that folder or subfolders will apply same logic