剃刀语法 / WebMatrix - C# 问题

3
在Windows Forms中,我可以创建一个名为“Authentication.cs”的类文件,并使用以下代码:
public class Authentication
{
    public string Name;

    internal bool Authenticate()
    {
        bool i = false;
        if (Name == "Jason")
        {
            i = true;

        }
        return i;
    }
}

在WebMatrix中,我可以插入一个名为“Authentication.cs”的新类文件,并插入上述代码。
在我的default.cshtml文件中,我这样做:
<body>
   @{
      Authentication auth = new Authentication();
      if(auth.Authenticated("jasonp"))
      {
         <p>@auth.Authenticated("jasonp");</p>
      }
   }
</body>

但是它不起作用!它适用于WinForms桌面应用程序,但在WebMatrix中不适用。我不知道为什么它不起作用。错误信息是:

"命名空间Authenticate不存在。您确定已引用了程序集等吗?"

因此,在我的default.cshtml文件顶部,我尝试了以下内容:

@using Authentication.cs;

这导致了完全相同的错误!

我无法找到任何文件说明如何将一个类文件“包含”到您的WebMatrix页面中。

感谢您的任何帮助!

谢谢!

3个回答

2
你导入的是命名空间,而不是文件。所以,Authentication 在哪个命名空间中?例如:

@using My.Utils.Authentication;

另外,在 Razor 调用中要省略 ;
<p>@auth.Authenticated("jasonp")</p>

您可以在代码中提供完全限定名称:
   @{
      var auth = new My.Utils.Authentication();
      if(auth.Authenticated("jasonp"))
      {
         <p>@auth.Authenticated("jasonp")</p>
      }
   }

(附注:您是否有意使用相同的值两次调用相同的方法?)

(附注:您是否故意使用相同的值两次调用相同的方法?)


是的,这两个方法调用是有意的。这不是为了客户或其他什么,只是为了学习等等。我没有命名空间,在WebMatrix中创建新的类文件时,没有命名空间(就像在winforms /桌面应用程序中一样)。但它一直在引用它,好像它确实有一个命名空间。@Marc,你从哪里得到“My.Utils”?我是否应该将这些类文件包含在名为My.Utils的文件夹中?如果这真的很菜鸟,对不起,但我完全迷失了。 - anon271334
@Lucifer,我只是发明了它。WebMatrix能让你使用命名空间吗? - Marc Gravell
没有;就我所看到的,没有。 - anon271334

1
只需将cs文件放入App_Code目录中,然后像这样做一些操作。
    @{
      Authentication auth = new Authentication();
      if(auth.Authenticated("jasonp"))
      {
         <p>@auth.Authenticated("jasonp");</p>
      }
   }

不需要添加 using。

另外,如果您想使用 .dll,则需要添加 using。

@using NameSpace.Authenication

@{
    Authenticated auth = new Authenicated();

 }

 @if(@auth.Authenticated("jasonp"))
 {
    <p>@auth.Authenticated("jasonp")</p>
 }

0
创建一个名为linkRef.cs的文件 代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;


public class linkRef
{
   public  linkRef() {
        //
        // TODO: Add constructor logic here   
    //
   }
}

将其放入一个名为 App_code 的文件夹中,然后使用 dot net 2012 发布到 bin 文件夹,最后上传 bin 文件夹。

创建App_Code文件夹,将cs文件放入该文件夹中,将App_Code转换为bin文件夹中的dll文件,然后上传bin文件夹(通过Visual Studio 2012 / 发布网站)。 - pejman

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接