简体   繁体   中英

Getting my class to work in asp.net C#

I have created C# classes before in non-web application projects. Normally, All you have to do is add a class file to the project and you can add an instance on the forms, no namespacing or using required. But I noticed in ASP.NET, when you create a class and try to create a instance, i'm getting errors saying the directive or assembly reference missing. I don't understand why? Okay, so most likely I have to take the hard way, and create a class library and use namespacing or add a reference yet STILL the same errors. I'm confused here why I can't seem to get this simple empty class working.

I currently have a class called Class1.cs in my App_code folder. I have an web form called About.aspx.

my class called Class1.cs

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

   namespace VideoWebsite1
  {
       public class Class1
    {

    public Class1()
    {
    }
    public string tag { get; set; }
   }
 }

my web form About.aspx

 using System;
 using System.Collections.Generic;
 using System.Linq;
 using System.Web;
 using System.Web.UI;
 using System.Web.UI.WebControls;
 using System.Data;
 using System.Data.SqlClient;
 using System.Web.Configuration;
 using VideoWebsite1;


  public partial class WebForm4 : System.Web.UI.Page
 {

      protected void Page_Load(object sender, EventArgs e)
      {
           Class1 p = new Class1();
           lbltag.text =(string) p.Tag;
      }
  }

update: Changing Build Action to compile to my class file fixed it. Thank you.

Your problem is here:

using VideoWebsite;

The compiler can't locate it so it's asking for a new reference to an assembly containing that namespace.

If that is a typo and you actually meant VideoWebsite1, you can remove it all together, since that is also the namespace of Class1.

If your Class1 is inside same project then yes you can refer it directly like the way you are intending to do but if you have created the class in a different project then include/add that project reference in your web project referenced dll list.

Then most probably the Build Action of the class is not set to compile . To check the same do below

Right click on the Class1.cs file under App_Code folder and check its Build Action property. If not set then set it accordingly.

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