Dynamics of HtmlHelper Extensions

两盒软妹~` 提交于 2020-01-14 18:50:10

问题


I'm accustomed to extension methods being presented by intellisense, after the 'this' type is keyed-in. But when I try this with HtmlHelper, the extension methods don't show - even though the 'using' statement is present. Why is this? To clarify, I'm doing this test from within a regular .cs file, rather than a .cshtml file. No good reason, I'm simply playing with the MVC namespace and language to "see how it ticks." I still don't know why the intellisense doesn't pick up all 4000 extensions (I exagerate, but there are many).

Speaking of thousands of extensions, why are these helper routines provided as extension methods? If typical static classes had been used, probably a sample razor signature would be:

@EditorExtensions.EditorFor<T>(...)

Seems doable, and the "Framework Design Guidelines" states that extensions should seldom be used, and preferably:

  1. only against interface types.
  2. only on types that cannot be re-deployed

It doesn't seem that any of the extension method "criteria" applies. This is why I would have expected regular static classes, with static methods to fill this roll. What was the rationale?

Update: Sample code of a non-extension helper (for further discussion)

public static class MyHelper
{
    public static MvcHtmlString Go(HtmlHelper foo){
        foo.Raw("Hello");
        return new MvcHtmlString("<p>What's up Doc</p>");
    }
}

回答1:


Not sure why IntelliSense is not showing HtmlHelper extension methods for you. Are you sure you are using System.Web.Mvc.Html?

The reason why these helpers were implemented as extension methods is because they often need to have access to various state associated with the request, the model, etc. It's a lot more difficult to achieve this goal while still making the helpers unit-testable if they were implemented as static methods.



来源:https://stackoverflow.com/questions/6106485/dynamics-of-htmlhelper-extensions

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