I looked around and couldn't find an easy solution.
I've tried @GetUserName
which doesn't work.
I've tried @ { GetUserName
which doesn't work.
There has to be an easy way to call a method from the razor view engine.
It is within a foreach
loop.
I need GetUserName(item.userID)
The below code is in my controller:
[ChildActionOnly]
public string GetUserName(int userID)
{
ProPit_User user = db.ProPit_User.Find(userID);
return user.username;
}
Other answers say it's bad practice; As with most things, that depends on how you use it.
Microsoft's shared layout as part of the MVC template,
_LoginPartial.cshtml
calls theSignIn
andSignOut
methods on the controller directly from the view:Using the
asp-controller
andasp-action
tag helpers on the hyperlink.Trying to call a controller action method directly from your view is usually a sign of bad design.
You have a few options, depending on what you are trying to do:
(1) is usually my default approach, often incorporating DisplayTemplates and EditorTemplates
For (3), e.g.
And the view:
Although you can obtain the controller instance from your view, doing so is plain wrong as it violates the whole MVC (and MVVM) paradigm, as the view should not be aware of its controller.
(The only possible reason I can think of where this would be useful would perhaps be for testing the controller from a mocked view, although even here, it should be possible to test the exposed controller functionality directly from unit tests):
The better way to have arrived at this result is for the controller to pre-populate, and pass all the data needed by the
View
, such as theuserName
, to a customViewModel
(as typed by the@model
directive at the top of the Razor page), or to theViewBag
dynamic.