直接从Razor View调用控制器动作方法 [英] Calling controller action method directly from Razor View

查看:49
本文介绍了直接从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:

  1. 避免调用该方法,而是将数据放入模型中,然后呈现模型
  2. 使用 Html.RenderAction
  3. 将该方法放在另一个类中,并使用常规函数语法.

(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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆