简体   繁体   English

从ASP.NET C#类页面实例化C#类

[英]Instantiating C# class from ASP.NET C# class page

I'm moving from PHP to ASP.NET/C#. 我正在从PHP迁移到ASP.NET / C#。 So far so good, but I don't understand how to instantiate a class within a ASP.NET C# class page. 到目前为止一直很好,但我不明白如何在ASP.NET C#类页面中实例化一个类。

For example I have login.aspx: 例如,我有login.aspx:

<%@ Page Language="C#" Inherits="Portal.LoginService" src="LoginService.cs" %>

<!DOCTYPE html>
<body>
    <form runat="server" id="login" name="login">           
        <p>Username:</p><input type="text" id="username" name="username" runat="server" />  

        <p>Password:</p><input type="password" id="password" name="password" runat="server" />

        <input type="submit" name="submit" OnServerClick="Post_Form" runat="Server" /> 
    </form>
</body>

LoginService.cs: LoginService.cs:

using System;
using System.Web.UI;
using System.Web.UI.HtmlControls;
namespace Portal {
public class LoginService : Page {

    protected HtmlInputControl username, password;

    public void Post_Form(object sender, EventArgs e) {

        if (username.Value != "" && password.Value != "") {
            //LOGIC HERE

            //This doesn't work
            CustomSanitize a = new CustomSanitize();                              
        }
    }
}
}

CustomSanitize.cs: CustomSanitize.cs:

using System;
namespace Portal {
    public class CustomSanitize {

        //instantiate here

        public string sanitizeUserPass() {
                return "logic here"
            }
    }
}

In other words, I want to use methods from different classes with the classes I have setup with ASP.NET C#. 换句话说,我想使用不同类中的方法和我使用ASP.NET C#设置的类。 Namespaces didn't work for me thus far. 到目前为止,命名空间对我来说并不起作用。

Thank you for any input. 谢谢你的任何意见。

If I undertstood you correctly, wrap CustomSanitize in a namespace ie: 如果我正确地执行了您, CustomSanitize包装在命名空间中,即:

namespace MyProject {
    public class CustomSanitize {

        //instantiate here

        public string sanitizeUserPass() {
                return "logic here"
            }
    }
}

Then wrap LoginService.cs in the same namespace. 然后将LoginService.cs包装在同一名称空间中。 ie

namespace MyProject {
    public class LoginService : Page {

        protected HtmlInputControl username, password;

        public void Post_Form(object sender, EventArgs e) {

            if (username.Value != "" && password.Value != "") {
                //LOGIC HERE

                //This doesn't work
                //CustomSanitize a = new CustomSanitize();                              
            }
        }
    }
}

You should now have access to CustomSanitize a = new CustomSanitize(); 您现在应该可以访问CustomSanitize a = new CustomSanitize();

You can also create more namespaces to split up your project. 您还可以创建更多名称空间来拆分项目。 ie namespace MyProject.Helper to wrap all your helper functions, then just add using MyProject.Helper to the top of the .cs file you wish to use the classes on. namespace MyProject.Helper来包装所有帮助函数,然后using MyProject.Helper添加到您希望使用类的.cs文件的顶部。

Edit: 编辑:

Please note, when adding a namespace to your project / wrapping classes in a namespace you need to reference them via that namespace via using or directly like MyProject.LoginService . 请注意,在命名空间中向项目/包装类添加命名空间时,需要通过using或直接像MyProject.LoginService通过该命名空间引用它们。 This must be done on aspx , ascx pages as well using the @ Page declaration . 这必须使用@ Page declarationaspxascx页面上完成。

If all of your above classes are in the same project, all that you should need to do is add a namespace. 如果您的所有上述类都在同一个项目中,那么您需要做的就是添加命名空间。 Check out the following example: Namespace tutorial 请查看以下示例: 命名空间教程

If you wish to use different namespaces within the same project, add a 'using' line of your own at the top, ie 如果您希望在同一个项目中使用不同的命名空间,请在顶部添加您自己的“using”行,即

using System;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using Utilities.Sanitizers;

namespace Services {

public class LoginService : Page {

protected HtmlInputControl username, password;

public void Post_Form(object sender, EventArgs e) {

    if (username.Value != "" && password.Value != "") {
        //LOGIC HERE

        //This doesn't work
        //CustomSanitize a = new CustomSanitize();                              
    }
}
}
}

using System;
namespace Utilities.Sanitizers
{
public class CustomSanitize {

    //instantiate here

    public string sanitizeUserPass() {
            return "logic here"
        }
}
}

in your CustomSanitize and loginservice class you are missing the namespace of your project. CustomSanitizeloginservice类中,您缺少项目的命名空间。

Along side that you might want to create a constructor for your class. 除此之外,您可能希望为您的类创建构造函数。 This is not necesary but will allows you to set default settings when you instantiate your class in another file. 这不是必需的,但允许您在另一个文件中实例化类时设置默认设置。 (an empty constructor is generated by the compiler when you not set it yourself. So the one in this code example is redundant. But just to show you.) (当你没有自己设置时,编译器会生成一个空构造函数。所以这个代码示例中的那个是冗余的。但只是为了向你展示。)

This goes as well as for creating overloaded constructers, allowing you to pass a variety of parameters to the constructers so the compiler will pick the correct one. 这与创建重载的构造函数一样,允许您将各种参数传递给构造函数,以便编译器选择正确的参数。

Though the main issue you are facing is probably not having namespaces included in your project. 虽然您面临的主要问题可能是您的项目中没有包含名称空间。 When files are in the same project you should add a namespace to all the classes within that project. 当文件在同一个项目中时,您应该为该项目中的所有类添加命名空间。 So they can be referenced between eachother. 因此可以在彼此之间引用它们。

Such as: 如:

using System;

namespace yourNameSpace
{
    public class CustomSanitize 
    {

        public CustomSanitize()
        {
            //Set what you need to set in the constructor
        }
        //instantiate here

        public string sanitizeUserPass() {
            return "logic here"
        }
    }
}

By Default, a namespace 'should' be added when you generate a new class from within visual studio. 默认情况下,从visual studio中生成新类时,应添加名称空间。 Unless you start with an empty code file every time. 除非您每次都以空代码文件开头。

One thing nobody has mentioned is that you don't need to do anything like this for user authentication. 没有人提到的一件事是你不需要做这样的事情来进行用户身份验证。 You should instead look at using the out of the box .net authentication and authorisation - see here: https://www.google.co.uk/search?q=.net+authentication&aq=0&oq=.net+authen&aqs=chrome.1.57j0l3j62l2.2451&sugexp=chrome,mod=19&sourceid=chrome&ie=UTF-8 您应该考虑使用开箱即用的.net身份验证和授权 - 请参阅此处: https//www.google.co.uk/search?q = .NET +authentication &aq = 0&oq = .NET + authen&aqs = chrome。 1.57j0l3j62l2.2451&sugexp =铬,MOD = 19&的SourceID =铬&即= UTF-8

However what everyone else is saying is correct. 然而,其他人都说的是正确的。 It's not working because you are missing a using statment (Intelisense should tell you that - you should infact be able to click the little underline bit, then click the add using link) 这是行不通的,因为你错过了一个使用的声明(Intelisense应该告诉你 - 你应该能够点击小的下划线位,然后点击添加使用链接)

Another thing you have done is added in the following:- 你做的另一件事是添加如下: -

protected HtmlInputControl username, password;

This isn't required in asp.net forms pages. 这在asp.net表单页面中不是必需的。 I'm assuming you have done a lot of manual work - .net is thankfully a lot easier than that. 我假设你已经做了很多手工工作 - 感谢网络比这简单得多。

This is more how the page should look:- 这更像是页面的外观: -

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Login.aspx.cs" Inherits="WebApplication2.Login" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:Label runat="server" AssociatedControlID="Username">Username:</asp:Label>     <asp:TextBox runat="server" ID="Username"></asp:TextBox>
        <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="Username" Display="Dynamic" Text="Username is required"></asp:RequiredFieldValidator>
        <br/>
        <asp:Label ID="Label1" runat="server" AssociatedControlID="Password">Password:</asp:Label> <asp:TextBox ID="Password" runat="server" TextMode="Password"></asp:TextBox>
    <asp:RequiredFieldValidator runat="server" ControlToValidate="Password" Display="Dynamic" Text="Password is required"></asp:RequiredFieldValidator>
        <br/>
        <asp:Button runat="server" Text="Login" ID="btnLogin" OnClick="btnLogin_Click" />
    </div>
    </form>
</body>
</html>

And the code behind: using System; 而背后的代码:使用System;

namespace WebApplication2
{
    public partial class Login : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void btnLogin_Click(object sender, EventArgs e)
        {
            Page.Validate();
            if (Page.IsValid)
            {
                string username = Username.Text;
                string password = Password.Text;
                //Logic here
            }
        }

    }
}

This takes care of all of the validation for you. 这将为您完成所有验证。 I would really recommend watching some of the videos here to help get up to speed: http://www.asp.net/web-forms , but you should also give serious consideration to using MVC as it better fits the way you are trying to develop 我真的建议你在这里观看一些视频来帮助我们加快速度: http//www.asp.net/web-forms ,但你也应该认真考虑使用MVC,因为它更符合你的尝试方式发展

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM