Access App_Code classes in Asp.Net

| October 21, 2010 | 2 Comments

You have added business classes(.cs) in App_Code folder. And now you want to use them either in .aspx page or in .aspx.cs page. Here are the solution for that.

I have added a single class with name as File1.cs in App_Code folder. See code snippet:

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

//Summary description for File1
namespace Department
{
public class File1
{
public File1()
{
//
// TODO: Add constructor logic here
//
}

public string ShowName()
{
return "I am from Class file in App_Code folder!";

}
}
}

To use in .aspx page

  1. Add tag <%@ Import Namespace=“Department”%>
  2. See code snippet:
    <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
    
    <%@ Import Namespace="Department" %>
    <!--<span class="hiddenSpellError" pre=""-->DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
        <title>My LAB</title>
    
        <script type="text/C#" runat="server">
            protected void btnTest_Click(object sender, EventArgs e)
            {
                File1 file = new File1();
                string var = file.ShowName();
                Response.Write(var);
            }
        </script>
    
    </head>
    <body>
        <form id="form1" runat="server">
            <div>
                <asp:Button ID="test" runat="server" Text="Test" OnClick="btnTest_Click" />
            </div>
        </form>
    </body>
    </html>
    

To use in .aspx.cs page

  1. Add reference to namespace by  using Department;
  2. See code snippet:
    using System;
    using System.Data;
    using System.Configuration;
    using System.Web;
    using System.Web.Security;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.Web.UI.WebControls.WebParts;
    using System.Web.UI.HtmlControls;
    using Department;  // Namespace referenced
    public partial class _Default : System.Web.UI.Page
    {
    protected void Page_Load(object sender, EventArgs e)
    {
    File1 obj = new File1();
    string var=obj.ShowName();
    Response.Write(var);
    }
    }
    

By this way we were able to access App_Code classes in asp.net. Share with us if you have some different solution.

Category: Asp.Net

Comments (2)

Trackback URL | Comments RSS Feed

  1. Sheila says:

    Nice, and to the point! Thanks!

  2. Gajendra says:

    Excellent article.

    Thanks for writing such short and sweet article.

Leave a Reply

%d bloggers like this: