tags:

views:

144

answers:

3

Hi, I have an asp.net web page (C# 2008) where the user would enter an EmployeeID, and when they tab out of the textbox (the page executes a validation code block in the codebehind), they get a messagebox prompting them to select one of two values from a dropdown listbox.

The code for the message prompt in the codebehind is :

Response.Write("<script>window.alert('Please select Alpha or Beta')</script>");

After the prompt is displayed, and the user clicks "ok" and returns to the page, the text on the page appears distorted (the text in labels are a size larger, the labels get wrapped to another line etc)

I tried putting a Response.Redirect("UserProfileMaint.aspx"); after the messagebox in the codebehind, but now, the messagebox does not appear;

So this is my squence:

  • User enters EmployeeID
  • If user has NOT selected Alpha or Beta, then show messagebox
  • If user HAS selected Alpha or Beta, then don't show messagebox

I want to display the messagebox validation, and ensure the appearance of the text on the page is not distorted. How can I do this?

+4  A: 

Response.Write writes directly to the output stream, placing it before <html> which the browser gets very confused by (causing your text issues). What you want to do instead is this:

ClientScript.RegisterStartupScript(GetType(), "alert", 
                                  "alert('Please select Alpha or Beta');", true);

ClientScript.RegisterStartupScript includes the script in the page to be run on load rather than put in the response too early. The last argument: true is telling it to wrap that alert in <script> tags, keeping your code-behind cleaner.

Nick Craver
wow. This works great. Thanks Nick
user279521
A: 

When you call Response.Redirect, that occurs on the server side, whereas you want the redirect to occur on the client side after a choice is made.

To do that, when you write your script with Response.Write (btw, there are much better ways to do this), you would have logic that determined what the user selected, and then based on the selection, either requery them for data, or set the location property of the inherent document object to the url you want to redirect to.

casperOne
+1  A: 

The best way to handle this would be to use Javascript and do Client side validation. If you really want to do server side validation then instead of showing a alert by using Response.Write you should use RegisterStartupScript or better show the message using a Label at the top.

HTH

Raja