直接从Razor View调用控制器动作方法 [英] Calling controller action method directly from Razor View
问题描述
我环顾四周,找不到简单的解决方案.
I looked around and couldn't find an easy solution.
我尝试了 @GetUserName
,该方法不起作用.
我尝试了 @ {GetUserName
无效.
I've tried @GetUserName
which doesn't work.
I've tried @ { GetUserName
which doesn't work.
必须有一种从razor视图引擎调用方法的简单方法.
There has to be an easy way to call a method from the razor view engine.
它在 foreach
循环中.
我需要 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;
}
推荐答案
尝试直接从视图中调用控制器操作方法通常是设计不良的迹象.
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:
- 避免调用该方法,而是将数据放入模型中,然后呈现模型
- 使用 Html.RenderAction
- 将该方法放在另一个类中,并使用常规函数语法.
(1)通常是我的默认方法,通常包含 DisplayTemplates和编辑器模板
(1) is usually my default approach, often incorporating DisplayTemplates and EditorTemplates
对于(3),例如
public static class Util
{
public string MyUtilMethod(int blah)
}
视图:
@Util.MyUtilMethod(1)
这篇关于直接从Razor View调用控制器动作方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!