Note that there are some explanatory texts on larger screens.

plurals
  1. POHow would you refactor page members out of ASPX code?
    text
    copied!<p>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.</p> <p>Code Behind:</p> <pre><code>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); } } } </code></pre> <p>ASPX Page:</p> <pre><code>&lt;%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="BadPassing._Default" %&gt; &lt;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"&gt; &lt;html xmlns="http://www.w3.org/1999/xhtml" &gt; &lt;head runat="server"&gt; &lt;title&gt;Bad Page&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;form id="form1" runat="server"&gt; &lt;div&gt; &lt;a href="http://www.google.com/search?q=&lt;%=this.numberOne %&gt;%2B&lt;%=this.numberTwo %&gt;"&gt; Add &lt;%=this.numberOne %&gt; and &lt;%=this.numberTwo %&gt; using google. &lt;/a&gt; &lt;/div&gt; &lt;/form&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>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.</p> <p>Is my understanding of why this the above technique is so bad correct, and if so, how would you best refactor this code?</p> <p>On a side note, is it incorrect to store stateless page-level services (like Random) as member variables of the page class?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload