Reputation: 73
I currently have this code.
public static class User
{
public static string GetUserName()
{
return Username;
}
}
I want to call in view @GetUserName()
, not User.GetUserName();
Is it possible to call a method inside a class in view MVC without referencing the class itself?
Upvotes: 4
Views: 570
Reputation: 82297
Just using @GetUserName()
wont work by default, as you state. The normal way to do this is to reference the class name and then use User.GetUserName();
. You clearly are already aware of that.
However, that doesn't mean part of this isn't possible. It shouldn't be done frivolously though. In order to directly call methods inside of your views you need to add them to your Views folder's web.config
file. Not the global one mind you, specifically the one in the views folder.
Inside of that file, you should find the namespace
element. This is where you can add your namespace reference to be able to directly call this method from your views.
<system.web.webPages.razor>
...
<pages pageBaseType="System.Web.Mvc.WebViewPage">
<namespaces>
<add namespace="System.Web.Mvc" />
<add namespace="System.Web.Mvc.Ajax" />
<add namespace="System.Web.Mvc.Html" />
<add namespace="System.Web.Routing" />
<add namespace="System.Web.Optimization" />
<!-- add the namespace containing static class User here -->
<add namespace="YourNamespace" />
</namespaces>
</pages>
</system.web.webPages.razor>
Once this is done, and recompiled, you will be able to use @User.GetUserName()
from the User
class in YourNamespace
in any view inside of that Views folder. If you are using areas, then you will need to do this for each view folder per area.
From my experience this use has been in extensions. Unfortunately it will not completely remove the need to use @User
, however it will remove the need to always be referencing the namespace when you do access that class.
Upvotes: 2
Reputation: 1502216
You can do this with a using static
directive, although I'd personally be concerned about the readability:
@using static User
...
<p>The user name is: @GetUserName()</p>
If User
is in a different namespace, you'd need this instead:
@using static WhateverNamespace.User
To repeat, I'd be very cautious about using this in terms of the readability... but it should work with no issues.
You could also add extension methods, although that isn't quite as neat. For example, my test app for this uses Razor pages, so I've got an IRazorPage
extension method:
namespace YourNamespace
{
public static class PageExtensions
{
public static string GetUserName(this IRazorPage view) => User.GetUserName();
}
}
Due to the way extension methods are looked up, you then need:
<p>The user name is: @this.GetUserName()</p>
The this.
is a little ugly, but at least you don't need to remember the class name.
Upvotes: 2