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:27

The first way is that use @using statement in .cshtml files, that imports a namespace to current file only, and the second:

In the "web.config" file in "Views" directory of your project (notice it is not the main web.config in project's root), find this section:

<system.web.webPages.razor>
  <pages pageBaseType="System.Web.Mvc.WebViewPage">
    <namespaces>
      <add namespace="System.Web.Mvc" />
      <add namespace="System.Web.Mvc.Ajax" />
      .
      .
      <!-- etc -->
    </namespaces>
  </pages>
</system.web.webPages.razor>

you can add your custom namespace like this:

<add namespace="My.Custom" />

that will add the namespace to all of .cshtml (and/or .vbhtml) files; also you can change views inheritance from here, like:

<pages pageBaseType="My.Custom.MyWebViewPage">

Regards.


UPDATE: Thanks to @Nick Silberstein to his reminder about areas! He said:

If you're working within an area, you must add the namespace within the Web.config under /Areas/<AreaName>/Views/ rather than /Views/

查看更多
浮光初槿花落
3楼-- · 2018-12-31 15:29

You can try this

@using MyNamespace
查看更多
余生请多指教
4楼-- · 2018-12-31 15:30

I think in order import namespace in razor view, you just need to add below way:

@using XX.YY.ZZ
查看更多
柔情千种
5楼-- · 2018-12-31 15:33

For namespace and Library

@using NameSpace_Name

For Model

@model Application_Name.Models.Model_Name 

For Iterate the list on Razor Page (You Have to use foreach loop for access the list items)

@model List<Application_Name.Models.Model_Name>

@foreach (var item in Model)
   {  
          <tr>
                <td>@item.srno</td>
                <td>@item.name</td>
         </tr>  
   }
查看更多
登录 后发表回答