Thursday, September 27, 2007

How to avoid unexpected postback after pressing Enter in textbox

You fill a form with many input fields. After filling first textbox you mechanically press Enter and see that the page are submitted to the server. Inasmuch as the rest of the fields stay blank the result of this submit is either saving incomplete data or a few validators of type "Field XXX is required." are shown. The well-known situation, is not it? It is not very good to allow such behaviour in a web application, especially because it easily can be corrected.

Of course, there are situations when this is useful (e.g.: you have a single search box and after typing a search keyword it is very convenient to start search by pressing Enter). But in the most cases such behaviour just
annoys visitors.

Surprisingly, but this inconvenience caused by built-in browser conveniences. :)

Convenience #1. If a form contains only textbox then regardless of the submit button presence pressing Enter will send the form to the server.

Candidate solutions
  • If design allows add one more textbox
  • If design allows set the textbox TextMode to "MultiLine". In this case the textbox is rendered as textarea element instead of input type="text"
  • Add an invisible text field (do not confuse with hidden field). See the below example:
<form ... >
<asp:TextBox ... >
<input type="text" style="display:none">

Convenience #2.
If the form contains input type="submit" or input type="image" pressing Enter submits the form using the focused input, if any, or first input on the form.

Candidate solutions
  • In order to rid of input type="submit" do not use a Button with UseSubmitBehavior="True"
  • In order to rid of input type="image" do not use ImageButton. It can be replaced with the following construction:
<asp:LinkButton ID="btn" runat="server">
<asp:Image id="im" runat=server ImageUrl="..." style="border:0px"/>

Appendix. Interrelation between ASP.Net controls and HTML elements.

ASP.Net ControlHTML Element
TextBox (TextMode="SingleLine")input type="text"
TextBox (TextMode="Password")input type="password"
TextBox (TextMode="Multiline")textarea
Button (UseSubmitBehavior="False")input type="button"
Button (UseSubmitBehavior="True")input type="submit"
ImageButtoninput type="image"

Tuesday, September 4, 2007

How to Register Stylesheet Created in Runtime

Here is an example from MSDN:
// Create a Style object for the  section of the Web page.
Style bodyStyle = new Style();
bodyStyle.ForeColor = System.Drawing.Color.Blue;
bodyStyle.BackColor = System.Drawing.Color.LightGray;
// Add the style to the header of the current page.
Page.Header.StyleSheet.CreateStyleRule(bodyStyle, this, "BODY");

It is the simple and handy method but has a few flaws.
1. Output is far from optimal. For example, following code that adds a border
someStyle.BorderColor = System.Drawing.Color.Red;
someStyle.BorderStyle = BorderStyle.Solid;
someStyle.BorderWidth = new Unit("1px");
produces this output
instead of
border:Solid 1px Red;

It has no matter if you don't pay attention to the size of pages you develop, but it is taken into consideration if you take into consideration your visitor's needs (sorry for tautology). But it's a trifle, of course. I mentioned it just for completeness. There is a more serious flaw.

2. Number of style attributes that can be registered in such way is very limited. You can't add padding or margin attributes or even particular border (e.g. border-left).

The code overview

Class StylesController has four public static methods:
//includes registered styles into page header
public static void RegisterStyleSheetBlock(Page page, string key, string styles)
LiteralControl ctrl = new LiteralControl(string.Format(@"<style type=""text/css"">
</style>", styles));
ctrl.ID = key;
//includes link to the newly created stylesheet file into page header
public static void RegisterStyleSheetInclude(Page page, string key, string styles)
byte[] bytes = System.Text.Encoding.UTF8.GetBytes(key);
string base64Key = Convert.ToBase64String(bytes).Replace('+', '!');
LiteralControl ctrl = new LiteralControl(string.Format(@"<link
type=""text/css"" rel=""stylesheet"" href=""{0}?key={1}""/>",
ctrl.ID = key;
HttpContext.Current.Session[base64Key] = styles;
//checks whether inline styles with specified key have been already registered
public static bool IsStyleSheetBlockRegistered(Page page, string key)
return (page.Header.FindControl(key) != null);
//checks whether a file with styles with specified key have been already registered
public static bool IsStyleSheetIncludeRegistered(Page page, string key)
return (page.Header.FindControl(key) != null);
The class StylesController implements IHttpHandler interface and serves as HttpHandler that produces the stylesheet file.
public class StylesController : IHttpHandler, System.Web.SessionState.IRequiresSessionState 
#region IHttpHandler Members
bool IHttpHandler.IsReusable
get { return false; }
void IHttpHandler.ProcessRequest(HttpContext context)
context.Response.ContentType = "text/css";
string key = context.Request["key"];
if (key != null)
object script = context.Session[key];
if (script != null)
HttpHandler has to be registered in web.config
<add verb="GET" path="StyleSheet.css" type="TypeName, AssemblyName"/>

where AssemblyName is the name of the assembly, where the class StylesController is located,
TypeName is the fully qualified name of the StylesController, including the namespace.

How to use

string styles = "div{padding:2px 5px;background-color:red;}";
if (!StylesController.IsStyleSheetBlockRegistered(this, "Red Divs"))
StylesController.RegisterStyleSheetBlock(this, "Red Divs", styles);
string styles2 = "a,a:link {text-decoration:none;background-image:url(img/back.gif);}";
if (!StylesController.IsStyleSheetIncludeRegistered(this, "New Links"))
StylesController.RegisterStyleSheetInclude(this, "New Links", styles2);

Source code - 1kB