Emitting an HTML string from anonymous type property in a repeated, dynamically-typed Partial View

对着背影说爱祢 提交于 2019-12-02 05:19:39
brichins

I found / compiled two solutions, neither of which am I really happy with. YMMV:

  1. Set ViewBag.MyField in the parent View before rendering each Partial View.

    Okay, I should have figured this one out a lot sooner, but had to get reminded of this possibility here because I rarely use it (preferring strongly-typed views whenever possible). I actually did try this early on, but due to the way I'm rendering the Partial multiple times it didn't seem to be appropriate. I actually still don't like it because in the parent view, I have to keep updating ViewBag.MyField before every call to @Html.Partial (6 times for my use case). This puts C# code and variable reuse way down the page in the middle of my content, where it is easy to miss and hard to maintain.

  2. Use reflection: object myField = ((Type)Model.GetType()).GetProperty("MyField").GetValue(Model);

    This is ultimately what I decided to go with for my use case. Even though reflection wasn't intended for this scenario, even though it requires a little extra error checking. The people who will be maintaining this are more familiar with reflection than .NET MVC, and it consolidates the code into one spot - on the page that it matters to, and at the top with the rest of the "server-side" manipulations. No repeated calls or hunting down references.

    I'm actually not entirely clear on why this works (also works with a dynamic instead of object), but I'm assuming it's something to do with the Razor engine is inspecting the myField object type directly for special rendering of a known type (IHtmlString), rather than seeing an unknown object and needing to access a property that is not known to exist at compile time.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!