Chris Dixon
Chris Dixon

Reputation: 9167

Strange .NET Core Partial View loading issue using a built string

A bit of background is that I'm trying to load a Navigation partial file per Sub Area that I'm in. Simple I originally thought...

Okay, so this works:

@await Html.PartialAsync("~/Areas/Admin/SubAreas/General/Views/Shared/_Navigation.cshtml")

And this does not work:

@if (ViewContext.RouteData.Values.ContainsKey("subarea"))
{
    // ViewContext.RouteData.Values["subarea"].ToString() comes out as "General"
    await Html.PartialAsync("~/Areas/Admin/SubAreas/" + ViewContext.RouteData.Values["subarea"].ToString() + "/Views/Shared/_Navigation.cshtml");
}      

I've tried removing the if statement to see if that was something to do with it, nope. I've tried string formatting like:

await Html.PartialAsync(string.Format("~/Areas/Admin/SubAreas/{0}/Views/Shared/_Navigation.cshtml", ViewContext.RouteData.Values["subarea"].ToString()));

Still no banana - the string definitely comes out as "~/Areas/Admin/SubAreas/General/Views/Shared/_Navigation.cshtml", and if I try changing this to a path that's invalid then it throws an error, so it's definitely finding the View, but just refuses to display it.

I can't seem to find anything about this around the net, but may be searching for the wrong thing. Any ideas out there?!

Upvotes: 0

Views: 222

Answers (2)

Jingo
Jingo

Reputation: 21

Lloyd's answer above was the fix I needed (thank you!), but another idiosyncrasy revealed itself to me as I was implementing it. Wrapping the code too closely in HTML caused the same issue.

<div>@{@await PartialAsync("View");}</div>

Failed to render the view, however I was able to simply by breaking it up as so

<div>
   @{@await PartialAsync("View");}
</div>

I'm not sure why this happens, I haven't looked much into that part of it yet, but I thought this was worth sharing in the same topic, since it's a different instance of the same issue with a different fix.

Upvotes: 0

Lloyd
Lloyd

Reputation: 29668

Try putting the @ back before the await partial.

I had issues with something like this last week and scratched my head for a while.

I think without the @ the view contents is kept code side and not marshalled back into the callers view.

Upvotes: 4

Related Questions