Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call a method inside a class in view without referencing the class itself?

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?

like image 377
tested hanes Avatar asked Oct 16 '25 13:10

tested hanes


1 Answers

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.

like image 105
Jon Skeet Avatar answered Oct 18 '25 07:10

Jon Skeet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!