Problem with passing non-literal text to the Html.Partial() extension method
I would like to pass the file name of a partial view as data retrieved from the viewbag as such:
<div id="Zone1">@Html.Partial(ViewBag.ZoneControl1)</div>
Where the "ZoneControl1" property of the 开发者_高级运维ViewBag is the name of the desired partial view retrieved from elsewhere (i.e. database, web service, etc.). If I include the text as a literal string i.e.:
<div id="Zone1">@Html.Partial("Controls/MyPartial")</div>
It works just fine. If I pass that literal string as a property of the ViewBag from the controller, or even just create a variable in the consuming view, i.e.:
@{string zone1 = "Controls/MyPartial";}
<div id="Zone1">@Html.Partial(zone1)</div>
It doesn't work. The page appears to be loading but never displays anything in the browser. Again, this works fine if I hardcode the partial view name, but not if it is passed as data from a variable or property. Anyone know why this is happening? If this is intended or unavoidable behavior, is there a workaround?
You can't use dynamic in Html.Partial
(which is what ViewBag
is) because it accepts only strings. One quick way around this would be to cast your ViewBag.ZoneControl
:
@Html.Partial((string)ViewBag.ZoneControl1)
As for the second part (zone1 = "Controls/MyPartial"
) I was unable to duplicate that.
The following code is what I wrote to test it and it works just fine.
@{ string zone1 = "Controls/MyPartial"; }
<div>@Html.Partial(zone1)</div>
I assume the answer with casting the ViewBag is what you're really looking for in this case.
Well, I have it working now and I'm not exactly sure what fixed it. I copied the razor code\markup and deleted that view and created a new view and pasted in the old code. The only difference was that when I created the new view, via the wizard, I specified to NOT use a master page and the resulting page had code to specify:
@{
Layout = null;
}
The original page was created using a master page and then I changed my mind and took out the layout directive entirely. Anyway, after making those changes, it WORKED! So, I initially surmised that the reason was that a view must specify "layout = null" if not using a master page. BUT, I then took out the "layout = null" code in this new page and it still worked! So... not sure what went wrong, but to sum up:
As @BuildStarted correctly noted, you can use a property of the ViewBag object as the partial view path, but you must cast it as a string for it to work properly. So, the premise for this question was incorrect and something else was mucking things up. Just not sure what.
精彩评论