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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With