Posts Tagged ‘ ’

ASP.NET Postback Class Members

Basically I had a class variable in an ASP.NET and found it was getting lost on page post-back.. well all you have to do is put that object in the Viewstate object already created for you.

public partial class MyPage : System.Web.UI.Page
        protected int MyInt;

        protected void Page_Load(object sender, EventArgs e)
            if (!IsPostBack)
		MyInt = 12345;
                ViewState["MyKey"] = MyInt;

	 This is called on a page post-back...
	protected void Event(object sender, EventArgs e)
			//Get factor list from viewstate
			MyInt = (int)ViewState["MyKey"];

			//Go nuts

Check If User Name Exists Using AJAX And C#

You could make sure the user name entered during the registration process of your website is unique before the submit button is clicked using AJAX and C#. To accomplish this create two aspx pages. The first (default.aspx in this example) is the registration page, and it contains a TextBox control with an onkeyup element that calls the updateOutput JavaScript function and a span tag to display the HTML returned by the XMLHttpRequest.send function. The second page (doajaxstuff.aspx) should only contain following tags:

  1. <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="doajaxstuff.aspx.cs"
  2. Inherits="ManualAJAX.doajaxstuff" %>
  3. <asp:literal runat="server" id="literal1" />

The html, title and body tags should be removed because the page contents will be added to the default.aspx page, which already has these tags. The C# code that checks if the user name exists is in the Page_Load event of doajaxstuff.aspx. It gets the user name from the query string and displays the result in a Literal control. To keep the example simple I returned “User name exists” or “OK”, but this could be changed to return an img tag to show a red cross image or a green tick respectively.

string[] usernames = { "admin", "administrator", "user1","user2",
                     "guest1", "guest2"};
protected void Page_Load(object sender, EventArgs e)
    string newUsername = Request.QueryString["q"];  

        literal1.Text = "User name exists";
        literal1.Text = "OK";

The JavaScript code below does the AJAX work. The updateOutput function checks first if the TextBox is empty, and exits if true. Then it creates an object called xmlHttp which is an XMLHttpRequest object or an ActiveXObject, depending on the user’s browser. XMLHttpRequest is supported in browsers from Internet Explorer 6, Opera 7.60, Mozilla 1.0, Netscape 7, Safari 1.2 and Konqueror 3.2. If the user has Internet Explorer 5 an ActiveXObject will be created, which basically does the same job. If the xmlHttp object is created the variable url will be assigned a string containing the page to call plus the query string, which is the string entered by the user in usernameTextBox.

The onreadystatechange event handler is assigned the name of the function StateChanged. This event occurs five times: when the request is initialized, set up, sent, being processed and completed. You could check which stage the request is in using the readyState variable (0, 1, 2, 3 and 4 respectively.) The if statement checks for 4 which is set when the HTML is downloaded to xmlHttp.responseText. The if statement also makes sure that xmlHttp.status is 200, which means no error occurred. If both these conditions are true the contents of xmlHttp.responseText are displayed in the span tag.

The open method sets the parameters of the request and contains three parameters; the request method, the URL of the request and a Boolean parameter that specifies the request should be executed asynchronously or not. The first parameter could be “GET”, “POST”, “HEAD” or “PUT”. The second parameter is the relative or full URL of the page to request. And the third parameter should be true so the page could be called asynchronously.

The send method executes the request. Because the open method’s first parameter is “GET”, send’s parameter is null. If open’s first parameter was “POST” it would be a string containing the request parameters.


<head runat="server">
<title>Manual AJAX</title>
<script language="javascript" type="text/javascript">
var xmlHttp;
function updateOutput(inputString)
if(inputString.length == 0)
document.getElementById("output").innerHTML = "";
xmlHttp = new XMLHttpRequest();
else if (window.ActiveXObject)
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
if(!xmlHttp || xmlHttp == null)
var url="doajaxstuff.aspx?q=" + inputString;
xmlHttp.onreadystatechange=StateChanged;"GET", url, true);
document.getElementById("output").innerHTML = "An error occured";
function StateChanged()
if((xmlHttp.readyState == 4) && (xmlHttp.status == 200))
document.getElementById("output").innerHTML = xmlHttp.responseText;
<form id="form1" runat="server">
Enter Username:
<asp:TextBox runat="server" ID="usernameTextBox"
onkeyup="updateOutput(this.value)" />
<span id="output"></span>
<head runat="server">     <title>Manual AJAX</title> <script language="javascript" type="text/javascript">         var xmlHttp; function updateOutput(inputString) {             if(inputString.length == 0)  {                 document.getElementById("output").innerHTML = "";   return;             } try  {                 if(window.XMLHttpRequest)       xmlHttp = new XMLHttpRequest();  else if (window.ActiveXObject)     xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");             if(!xmlHttp || xmlHttp == null)  {                     return;                 } var url="doajaxstuff.aspx?q=" + inputString;                 xmlHttp.onreadystatechange=StateChanged;       "GET", url, true);                 xmlHttp.send(null);             }             catch(e)             {                 document.getElementById("output").innerHTML = "An error occured";             }         } function StateChanged() {             if((xmlHttp.readyState == 4) && (xmlHttp.status == 200))  {                 document.getElementById("output").innerHTML = xmlHttp.responseText;             }         }     </script> </head> <body>     <form id="form1" runat="server">     <div>         Enter Username:         <asp:TextBox runat="server" ID="usernameTextBox" onkeyup="updateOutput(this.value)" />         <span id="output"></span>     </div>     </form> </body>

For this example the C# code in the doajaxstuff.aspx page searches an array containing the user names. This could be changed to search through the users in the aspnetdb database using the Membership.GetUser static function. I should also mention that the user can ignore the result of this validation check and submit a name that exists. To prevent this, the same validation should be done in the Submit button’s code.

Silverlight 4 debugging and Firefox 3.6.4+

I’ve been stuck on this for a few days.

At the moment, Firefox 3.6.4 (and newer) have a new functionality called ‘Crash protection’, which is quite nice.

For customers.

It now runs the plugins in a separate process called ‘plugin-container.exe’ (look in your task manager).

But for developers it’s quite the hassle, since Visual Studio attaches itself to Firefox but NOT to this process. So no more Silverlight debugging for you!

Luckily there are two options for you!

The first option is the most straight forward, but has to be done each time. Use Visual Studio to attach itself to plugin-container.exe, refresh the website, and BAM, you’re up and running!

On the next screen click ‘plugin-container.exe’. There might be 2, if so, select the one with ‘Silverlight’ in the ‘Type’ column:

And hit ‘Attach’.

While this solution is adequate for when you need to debug it one time at a day, but for me, I only debug in Firefox, and when necessary I use Internet Explorer. For that you can go to your ‘about:config’ in Firefox, disable ‘dom.ipc.plugins.enabled.npctrl.dll’ (set it to false).