Wednesday, April 29, 2015

ASP.Net C# Creating an AutoFocus property in your Master Page

Recently I posted about Accessing Master Page Controls from Content Pages. This same technique can be used to create an AutoFocus property that you can use generically from your content pages.

   <!-- auto focus -->  
   <asp:PlaceHolder ID="pnlAutoFocus" runat="server">  
     <script language="javascript" type="text/javascript">  
       $(document).ready(function () {  

Notice we're using jQuery and we're targeting the first input control that is enabled, visible, and does not have a noautofocus class. The noautofocus class allows us to still use the AutoFocus feature on a page, but exclude certain controls if necessary, for example:
 <asp:DropDownList ID="ddlState" CssClass="form-control noautofocus" ClientIDMode="Static" runat="server" />  

Next we expose the AutoFocus property in the Base.Master code-behind.

     public bool AutoFocus  
         return pnlAutoFocus.Visible;  
         pnlAutoFocus.Visible = value;  

Now you can access the AutoFocus property from your content pages like so.

  <%@ Page Language="C#" MasterPageFile="~/Base.Master" AutoEventWireup="true" CodeBehind="Test.aspx.cs" Inherits="Sandbox.Web.Test" %>   
  <%@ MasterType VirtualPath="~/Base.master" %>  

   private void Page_PreLoad(object sender, System.EventArgs e)  
      // auto focus  
      Master.AutoFocus = true;  


Why use this approach? Well for me it allows me to keep things generic. Sure you could manually set the focus of the appropriate web control from page to page in its respective code-behind (or with JavaScript); however, this approach lets you just build the form and basically will focus things for you automatically, and you only have to handle exceptions, which can be accomplished with the noautofocus class or by disabling the AutoFocus property for the entire page.

Matt Pavey is a Microsoft Certified software developer who specializes in ASP.Net, VB.Net, C#, AJAX, LINQ, XML, XSL, Web Services, SQL, jQuery, and more. Follow on Twitter @matthewpavey