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

查看:32
本文介绍了直接从 Razor 视图调用控制器操作方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我环顾四周,找不到简单的解决方案.

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 视图调用控制器操作方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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