ASP MVC Compile-time include of partial view

2019-02-19 08:53发布

问题:

I have two different views that makes upwards of 500 partial view calls each to a common partial view. Good design tells me that I should leave the partial view where it is and reference it from both overlying views to prevent code duplication. Unfortunately, performance suffers - copy-pasting the partial view in each of the other two views yields a 300ms improvement.

Is there anyway that I can, include a partial view in an overlying view, reaping the performance benefits of not using the actual Partial() call, while at the same time not having to maintain duplicate code? Note - I realize that I could write some sort of VS add-on that would copy-paste the view code, but I am looking for other options...

回答1:

Things to try that might improve performance:

  • Use @{Html.RenderPartial("_foo");} instead of @Html.Partial("_foo") to include the partial
  • Always do your benchmarking in Release mode. Lots of optimizations and caching are performed by ASP.NET MVC in contrast to Debug mode.

If the previous 2 suggestions didn't yield the required performance then you might try replacing the partial with a custom HTML helper that will generate the HTML fragment. This could work if the HTML of the partial is not very complex.



回答2:

I'm going to date myself here, but have you considered using a server side include to inject the partial view's code, rather than calling out to it? I have absolutely no evidence, empirical or subjective, that this would be any faster. Just something worth trying.