How do i declare and use a C# object in an .ASPX file?
Question
i am making a website using asp.net and C# and well i got stuck at the first hurdle, i found out that to use code you use the <% %> with asp but i dont get how i would create an object of my class to use in the aspx file?
I think its syntax more than anything i cant seem to get to work.
Thanks,
Ash
Solution
If you need to declare a global object to be accessible everywhere in your page:
<script runat="server">
// ObjectType: Your class name
// Name: Your instance (variable) name.
ObjectType Name = new ObjectType();
</script>
If you just need a local variable:
<%
ObjectType name = new ObjectType();
name.SomeMethod();
%>
By the way, you should have good reasons for using these kind of things in ASP.NET. There are usually better ways to encapsulate user interface elements in user controls and master pages.
Side note: You can't use using
directives in .aspx
files. If you need to import some namespace in your code, you should add <%@ Imports Namespace="SomeNamespace" %>
directives right after your <%@ Page %>
directive.