How do I import a namespace in Razor View Page?

2018-12-31 14:44发布

How to import a namespace in Razor View Page?

10条回答
无与为乐者.
2楼-- · 2018-12-31 15:09

I found this http://weblogs.asp.net/mikaelsoderstrom/archive/2010/07/30/add-namespaces-with-razor.aspx which explains how to add a custom namespace to all your razor pages.

Basically you can make this

using Microsoft.WebPages.Compilation;
public class PreApplicationStart
{
   public static void InitializeApplication()
   {
       CodeGeneratorSettings.AddGlobalImport("Custom.Namespace");
   }
}

and put the following code in your AssemblyInfo.cs

[assembly: PreApplicationStartMethod(typeof(PreApplicationStart), "InitializeApplication")]

the method InitializeApplication will be executed before Application_Start in global.asax

查看更多
人气声优
3楼-- · 2018-12-31 15:09

One issue that you must know is that when you import a namespace via web.config in Views folder, that namespace is imported JUST for views in that folder. Means if you want to import a namespace in an area views, you must also import that namespace, in that area's web.config file, located in area's Views folder;

查看更多
路过你的时光
4楼-- · 2018-12-31 15:12

Finally found the answer.

@using MyNamespace

For VB.Net:

@Imports Mynamespace

Take a look at @Javad_Amiry's answer if you want to include a namespace across the app.

查看更多
柔情千种
5楼-- · 2018-12-31 15:15

In ASP.NET MVC 3 Preview1 you can import a namespace on all your razor views with this code in Global.asax.cs

Microsoft.WebPages.Compilation.CodeGeneratorSettings.AddGlobalImport("Namespace.Namespace");

I hope in RTM this gets done through Web.config section.

查看更多
闭嘴吧你
6楼-- · 2018-12-31 15:16

"using MyNamespace" works in MVC3 RTM. Hope this helps.

查看更多
与君花间醉酒
7楼-- · 2018-12-31 15:17

For Library

@using MyNamespace

For Model

@model MyModel
查看更多
登录 后发表回答