Reputation: 55
I'm using VisualStudio 2013 Express for WEB, and I created an empty web application, and then added a new web form.
I'm trying to learn ASP.NET, and I learned that in the session / page life cycle there is Page_Load where I can execute thing that will happen just after the page loads. The thing is I learned that it is possible to put the Page_Load event under <script>
before the <HTML>
tag.
(The aspx file name is Register) When I try this:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Register.aspx.cs" Inherits="Learning.Register" %>
<!DOCTYPE html>
<script runat="server">
int randomnumber = 0;
public void Page_Load()
{
Random rnd = new Random();
randomnumber = rnd.Next(100000, 1000000);
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<% Response.Write(randomnumber); %>
</div>
</form>
</body>
</html>
All I get is 0 for some reason.
Also, I noticed that under Register.aspx.cs I have this:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace Learning
{
public partial class Register : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
}
}
Upvotes: 1
Views: 9179
Reputation: 45490
in the script tag you need to have base.OnLoad(e)
protected void Page_Load(object sender, EventArgs e)
{
base.OnLoad(e)
Random rnd = new Random();
randomnumber = rnd.Next(100000, 1000000);
}
That's because you are overriding the behavior of the base class, and if you don't call base.OnLoad(e)
then Page_Load
would not run in the markup side.
Upvotes: 1
Reputation: 3681
You can definitely put the server side code in aspx using script tag. But the page load syntax should exactly match as it is in your code behind(.cs file)
Page_Load(object sender, EventArgs e)
In your script code you have just Page_Load() which does not trigger at all. If you need this to be excecuted then you need to remove the function in the code behind and replace the method signature in the script tag
Upvotes: 3