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.

Base.Master
   <!-- auto focus -->  
   <asp:PlaceHolder ID="pnlAutoFocus" runat="server">  
     <script language="javascript" type="text/javascript">  
       $(document).ready(function () {  
         $(':input:enabled:visible:not(.noautofocus):first').focus();  
       });  
     </script>  
   </asp:PlaceHolder>  

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.

Base.Master.cs
     public bool AutoFocus  
     {  
       get  
       {  
         return pnlAutoFocus.Visible;  
       }  
       set  
       {  
         pnlAutoFocus.Visible = value;  
       }  
     }  

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

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

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

JSFiddle:
http://jsfiddle.net/mpavey/4r1ttfgy/

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

0 comments: