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

后端 未结 1 887
野的像风
野的像风 2021-01-23 21:44

I am passing an anonymous type into a dynamic partial view as part of the @model, and one of the properties is a string that contains some HTML. When I use the

相关标签:
1条回答
  • 2021-01-23 21:57

    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.

    0 讨论(0)
提交回复
热议问题