【问题标题】:Create a Simple Class and Call Its Method from a cshtml File without using App_Code在不使用 App_Code 的情况下从 cshtml 文件创建一个简单的类并调用其方法
【发布时间】:2014-09-16 22:47:44
【问题描述】:

我看过这个相关的问题Creating and Simple Class and Calling a Method from a cshtml File。我们如何在不使用 App_Code 文件夹的情况下做到这一点?

在我的项目的根目录中,我有一个 Something.cs 类:

public class Something 
{
    public static void DoIt()  
    { 

    }
}

在我的项目的根目录中,我还有 index.cshtml 和以下代码:

@Something.DoIt()

名称Something 在 index.cshtml 的当前上下文中不存在。

【问题讨论】:

  • @Something.DoIt() 表示你正在渲染一些东西,所以DoIt() 方法应该有返回值。顺便问一下,Something 课你在哪里上课?

标签: c# asp.net razor


【解决方案1】:

您是否尝试过在 cshtml 文件中引用项目库

@using ProjectName;

或者像这样引用对象@ProjectName.Something.DoIt()

【讨论】:

  • 我可以在生产环境中执行此操作吗?我的意思是在生产中添加cs文件
【解决方案2】:

如果您在 .cshtml 顶部或任何 HTML 字符串模板(如 for 循环)内访问它,那么

@{
   MvcDemo.Something.DoIt();
}

在 BeginForm 或其他里面

@using (Html.BeginForm())
{
 MvcDemo.Something.DoIt();
}

请注意 MvcDemo 是命名空间,如果你直接写 @MvcDemo.Something.DoIt() 可能会出错。

【讨论】:

    【解决方案3】:

    这是我需要采取的步骤。

    1. 创建一个名为 SomeThing.cs 的文件。
    2. 将上述文件放在 csproj 根目录中的任意位置。
    3. 将所述文件添加到 .csproj (这是我忘记做的)。
    4. 使用方法DoIt() 将类SomeThing 添加到所述SomeThing.cs 文件中。
    5. 从 SomeFile.cshtml 文件中调用其方法。

    例如SomeFile.cshtml

    @SomeThing.DoIt() // this assumes class SomeThing is NOT inside a namespace.
    

    我的问题是没有将 SomeThing.cs 添加到 .csproj。

    【讨论】:

    • 请使用您问题上的编辑链接添加更多信息。 Post Answer 按钮应仅用于问题的完整答案。
    • @jmoerdyk 我更新了答案以使其更完整。
    • @Ian 我是这个问题的作者。
    猜你喜欢
    • 2011-03-22
    • 1970-01-01
    • 1970-01-01
    • 2014-03-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-10
    相关资源
    最近更新 更多