I am working on an ASP.NET website which requires all server-side code to be done using the “code in front” model — I have to use server-side script blocks on .aspx, .ascx or .master pages. I would like to define a class (call it Vehicle) once within a server-side script and them import that definition on other pages or controls as needed. Is this possible?
I’d like to define this class somewhere (user control?):
<script runat="server">
Public class Vehicle
{
public int Id {get; set; }
public string Name{ get; set; }
}
</script>
Then create an instance on site.master:
<script runat="server">
//todo: include the script block containing the definition of Vehicle
public Vehicle v = new Vehicle{ Id=1, Name="Car1"};
</script>
Then use it on default.aspx:
<script runat="server">
Response.Write (master.v.Name);
</script>
I know this works against ASP.NET but the point is that I can’t recompile the site or deploy another assembly, I can’t create .cs source files, only asp.net pages or controls.
You won’t be able to keep all of your classes inside of .as?x files, but I gather that what you want is “compile on the fly”. You can do the same thing, and still put your classes into .cs files as is appropriate, by creating an App_code directory. As stated here, code in that folder is automatically compiled at run time.