I have inherited a project that uses the following pattern for passing parameters from the code behind to the aspx page. I know this is wrong, but I am on the fence on the best way to refactor it.
Code Behind:
using System;
using System.Web;
namespace BadPassing
{
public partial class _Default : System.Web.UI.Page
{
private Random rnd = new Random(); //Is this bad?
protected int numberOne; //this is bad
protected int numberTwo; //this is bad
protected void Page_Load(object sender, EventArgs e)
{
numberOne = rnd.Next(100);
numberTwo = rnd.Next(100);
}
}
}
ASPX Page:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="BadPassing._Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Bad Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<a href="http://www.google.com/search?q=<%=this.numberOne %>%2B<%=this.numberTwo %>">
Add <%=this.numberOne %> and <%=this.numberTwo %> using google.
</a>
</div>
</form>
</body>
</html>
My understanding is that the numberOne and numberTwo are not thread-safe, and could cause incorrect behavior if two people loaded the page at the same time. Furthermore, if the page relied on numberOne and numberTwo to store values between postbacks, multiple simultaneous users would cause unexpected results.
Is my understanding of why this the above technique is so bad correct, and if so, how would you best refactor this code?
On a side note, is it incorrect to store stateless page-level services (like Random) as member variables of the page class?