问题
I have an ASP.NET (C#) application, written with VS 2008, that uses CodeBehind files and master pages. There are also other classes and extension methods all in the same namespace. Now on some pages my classes and methods are undefined from inline code, like <%=MyClass.MyMethod().ExtensionMethod()%>. I can write <%=MyNamespace.MyClass.MyMethod()%>, but 1. it's unnecessarily longer and 2. I cannot use extension methods then. On most pages, it works, but on some it doesn't.
I can blindly (without IntelliSense) type in the code though and it will compile fine, but when accessing the page, it throws some HttpCompiler exception telling me that the class/method is undefined. It suggests me to add a "using" or a reference. But how am I supposed to insert a "using [namespace]" on a .aspx page in the code view? This is only available in C# code, not in HTML code. And I definitely don't need a reference because it's all in the same project, even in the same namespace.
Does anybody know why this isn't working sometimes? What's the reason at all, I don't even know where to start looking for the problem, not to mention a solution...
回答1:
<%@ Import Namespace="Namespace.Containing.ExtensionMethod" %>
Or if you want it to apply globally on all pages you could use web.config:
<pages>
<namespaces>
<add namespace="Namespace.Containing.ExtensionMethod"/>
</namespaces>
</pages>
来源:https://stackoverflow.com/questions/1886849/why-are-my-classes-not-available-from-asp-net-inline-code