Should I create HtmlHelper extension method to reduce duplication of rendering partial views?
Let's say I have a Statistic view that will display on different pages. Without any helpers, I have to using following code:
@section Statistic{
@Html.RenderAction("Index", "Statistic", new { id = Model.UserId });
}
But with creat开发者_StackOverflow社区ing a helper, I can write something like:
@section Statistic{
@Html.Stats().For(Model.UserId);
}
Then any future changes in Controller, ActionName or parameter of the Statistic controller will need to be changed in 1 place which is in my StatsHtmlHelper
Some of my colleagues complain that this helper does nothing but call the RenderAction then it should not exist. What is your opinion?
With creating helper method, you reduce the complexity of calling RenderAction, ActionLink and such methods, and get rid of the "magic strings". But for every different action, you have to create another helper with your approach(!), and this may be creating other complexity, especially when there already exist community tools for making life simpler in cases like that. If you do that for statistics, why wouldn't you do that for every other action in your application? I would use T4MVC with its RenderAction, ActionLink
overloads that accept ActionResult
. With it, you get rid of magic strings and get compile time exceptions when your controller, action or parameter signature changes. With exact places marked with error by compiler, fixing them is easier. With T4MVC, your statistics rendering line would be:
@{Html.RenderAction(MVC.Index.Statistic(Model.UserId));}
And T4MVC methods are for general approach. You can simply use them for every single action throughout your project
精彩评论