Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to use @using in my razor syntax view in ASP.Net MVC 5

And yes, I searched it on google I could not find the exact answer.

So, When to use @using SomeModel in my razor syntax view. I am new to ASP.net MVC 5 and I know that each view can be strongly bound to a model or a viewModel and we use @model ModelName. What will be the situation when I will have to use @using in my razor view. Any example would be highly appreciated.

like image 561
Unbreakable Avatar asked May 13 '17 13:05

Unbreakable


1 Answers

Every time you need to import a namespace inside your view. This is the same as when you import a namespace in a standard C# code file.

So, if you need to use a type which is declared in a different namespace than the View one, you'll need to add a using statement before using that type.

@using OtherNamespace

@{
    var example = new ExampleClass(); // full name is OtherNamespace.ExampleClass
}

Be aware that there is another method for importing namespaces inside Views in MVC 5, which uses the Web.config file located in "Views" folder (note that this is not the global Web.config file). You may add further namespaces by adding the following parts:

<system.web.webPages.razor>
    <pages pageBaseType="System.Web.Mvc.WebViewPage">
        <namespaces>
            <add namespace="System.Web.Mvc" />
            <add namespace="OtherNamespace" />
        </namespaces>
    </pages>
</system.web.webPages.razor>

This way you will not need to add a @using statement inside the .cshtml file.

[Edit]

Regarding the @model statement inside a view, there are essentially two options:

@using MyNamespace.MyNestedNamespace
@model MyModel

Or, if you think you will not need any other types from that namespace:

@model MyNamespace.MyNestedNamespace.MyModel

There is no real difference, is up to you what you think is better for that view.

like image 194
Federico Dipuma Avatar answered Oct 11 '22 23:10

Federico Dipuma