简体   繁体   中英

Instantiating C# class from ASP.NET C# class page

I'm moving from PHP to ASP.NET/C#. So far so good, but I don't understand how to instantiate a class within a ASP.NET C# class page.

For example I have 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:

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:

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#. Namespaces didn't work for me thus far.

Thank you for any input.

If I undertstood you correctly, wrap CustomSanitize in a namespace ie:

namespace MyProject {
    public class CustomSanitize {

        //instantiate here

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

Then wrap LoginService.cs in the same namespace. 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();

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.

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 . This must be done on aspx , ascx pages as well using the @ Page declaration .

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 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.

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. 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

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)

Another thing you have done is added in the following:-

protected HtmlInputControl username, password;

This isn't required in asp.net forms pages. 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;

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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