调用控制器的操作方法直接ROM的Razor视图 [英] Calling controller action method directly rom Razor View
问题描述
我环顾四周,找不到一个简单的解决方案。
我试过 @GetUserName
这是行不通的。结果
我试过 @ {GetUserName
这是行不通的。
必须有一个简单的方法来调用从剃刀视图引擎的方法。
这是一个的foreach
循环中。
我需要 GetUserName(item.userID)
下面code是在我的控制器:
[ChildActionOnly]
公共字符串GetUserName(INT用户ID)
{
ProPit_User用户= db.ProPit_User.Find(用户ID); 返回user.username;
}
试图直接从您的视图调用控制器的操作方法通常是设计不良的征兆。
您有几种选择,这取决于你正在尝试做的:
- 避免调用该方法,而不是把数据在模型中,并渲染模型
- 使用<一个href=\"http://haacked.com/archive/2009/11/18/aspnetmvc2-render-action.aspx/\">Html.RenderAction
- 把方法在另一个类,并使用正常功能语法。
(1)通常我默认的态度,常合并<一个href=\"http://www.growingwiththeweb.com/2012/12/aspnet-mvc-display-and-editor-templates.html\">DisplayTemplates和EditorTemplates
有关(3),例如
公共静态类的Util
{
公共字符串MyUtilMethod(INT等等)
}
和视图:
@ Util.MyUtilMethod(1)
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;
}
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:
- Avoid calling the method, instead put the data in your model, and render the model
- Use Html.RenderAction
- Put the method in another class and use normal function syntax.
(1) is usually my default approach, often incorporating DisplayTemplates and EditorTemplates
For (3), e.g.
public static class Util
{
public string MyUtilMethod(int blah)
}
And the view:
@Util.MyUtilMethod(1)
这篇关于调用控制器的操作方法直接ROM的Razor视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!