【问题标题】:c# razor functions in external filec# razor 外部文件中的函数
【发布时间】:2025-12-01 00:55:01
【问题描述】:

我的 cshtml 页面上有一个函数可以检查输入的电子邮件是否有效,它可以正常工作,但是我现在需要将它移动到外部文件中,以及我创建的所有其他函数,我不能似乎找到有关此的任何信息,谁能告诉我该文件应该具有什么文件扩展名?我知道它需要进入 App_Code 文件夹,我应该对我的功能做一些特别的事情吗?以及如何在我的网页上调用它?我的讲师实际上没有任何关于这方面的笔记。

bool IsEmail(string email) {
    //declare the return variable 
    bool rst = false;

    System.Text.RegularExpressions.Regex regex = new System.Text.RegularExpressions.Regex(@"^([\w\.\-]+)@([\w\-]+)((\.(\w){2,3})+)$");
    // does the string follow the regex structure?
    System.Text.RegularExpressions.Match match = regex.Match(email);
    //if yes
    if (match.Success){
        rst = true;
    } else {
        rst = false;   
    }

    return rst; 
}

提前致谢

【问题讨论】:

  • @Improwse 只是一个快速的建议 - 您可以将最后的代码重构为 return match.Success;,因为您正在根据布尔值分配一个布尔变量。

标签: c# html function razor


【解决方案1】:

App_Code的新文件中:

public static class GodObject {
    public static bool IsEmail(string email) {
        //declare the return variable 
        bool rst = false;

        System.Text.RegularExpressions.Regex regex = new System.Text.RegularExpressions.Regex(@"^([\w\.\-]+)@([\w\-]+)((\.(\w){2,3})+)$");
        // does the string follow the regex structure?
        System.Text.RegularExpressions.Match match = regex.Match(email);
        //if yes
        if (match.Success){
            rst = true;
        } else {
            rst = false;   
        }

        return rst; 
    }
}

然后,您几乎可以在任何地方引用GodObject.IsEmail(...)

这可能是您的教授所追求的,但是,有更好的方法来进行此验证。

【讨论】:

  • 在尝试后我得到“名称'GodObject'在当前上下文中不存在”
  • 你把它放在什么命名空间里?您必须做两件事之一 - 完全限定 Namespace.ClassName.MethodName 中的引用,或者您可以添加 @using 语句以在您的 cshtml 中包含命名空间。
  • 是的!我知道了谢谢!我还在 cshtml 文件中使用了 @functions{} ,我删除了它并将其重命名为 .cs 文件,它现在可以正常工作了!谢谢你:)