Rules to Better Website Development - ASP.NET

Hold on a second! How would you like to view this content?
Just the title! A brief blurb! Gimme everything!
  1. Do you know how to create nice URLs using ASP.NET 4?

    There are a lot of reasons to have nice URLs for your website:
    • Easy to remember
    • Easy to navigate 
    • Better for search engines
    Bad example – This URL is impossible to remember for your users, and even search don’t like these URLs
    Figure: Bad example – This URL is impossible to remember for your users, and even search don’t like these URLs
    Good example – Nice clean URL, easy to remember, easy to guess where I am and good for search engines
    Figure: Good example – Nice clean URL, easy to remember, easy to guess where I am and good for search engines

    With ASP.NET 4 it is easy to create this URLs. The ASP.NET team includes routing features, known from the MVC web framework.
    Add a route in Global.asax

    protected void Application_Start(object sender, EventArgs e)
    //RouteTable and PageRouteHandler are in System.Web.Routing
    new Route("products/{productname}",
    new PageRouteHandler("~/ssw/Products/ProdCategoryList.aspx")));
    Figure: Example on how to route{everything} to the page

    Note: There is no dependency on the MVC framework in order to use this code.
    Note: IIS7 has a module called URL rewrite module that can do this functionality without changing any code. Just a configuration of a "Rule" in the IIS Manager.

  2. Do you know how to filter data?

    It is difficult for users to find their required records in a huge amount of data, so adding the filter data functionalities is very useful. 

    The standard DataGrid of ASP.NET doesn't include this functionality, developers need to implement it by themselves.

    Bad Example - implement data filter manually
    Figure: Bad Example - implement data filter manually

    Fortunately, RadGrid supplies this perfect feature.

    Good Example - add an attribute to filter data
    Figure: Good Example - add an attribute to filter data

    Developer can turn this feature on by setting the AllowFilteringByColumn="True".

  3. Do you use jQuery for making a site come alive?

    To please customers every business knows they need to keep their services and offerings fresh and up-to-date. The same is true for websites. In order to attract new traffic, we should make the website vivid.
    Bad example – there is no response when mouse is over the image
    Figure: Bad example – there is no response when mouse is over the image
    Good example – apply the different style when mouse is over
    Figure: Good example – apply the different style when mouse is over
            $("p").hover(function () {
                $(this).css({ "background-color":"yellow", "font-weight":"bolder" }); },
                function () { 
                    var cssObj = { "background-color": "#ddd", 
                    "font-weight": "", 
                    color: "rgb(0,40,244)"
    Figure: Mouse hover sample
  4. Do you use jQuery Tooltips to save drilling through?

    It is common when we browse a list page, we have to click the "More..." or "Details" button to view the item detail. This process takes more time because we need to wait for the loading of the detail page.

    To improve the performance, we can use jQuery plus CSS to show tooltips in the list page that can let users determine which item detail they want to see.
    Bad Example - redirect to a new page to view the detail
    Figure: Bad Example - redirect to a new page to view the detail
    Good Example - show tooltip when mouse is over in the list
    Figure: Good Example - show tooltip when mouse is over in the list
  5. Do you use MSAjax for Live Data Binding which saves round trips?

    In old versions of ASP.NET AJAX the UI control couldn't get notification if the source had been changed. Developers had to write the extra code to refresh the value.

    In ASP.NET AJAX version 4.0, there is a new feature called "Live Data Binding", which means when there's any change in the data source, the changes are reflected to the data bound interface instantly and vice versa. 
    Binding Modes:
      This is the default binding mode. Two-way binding on an input control, and one-way binding on a context-type elements such as spans.
      <b>Name: </b><input id="name" type="text" value="{binding name, mode=auto}" />
      <b>Echo: </b><span id="nameDisplay">{binding name, mode=auto}</span>
      Figure: When you update either textbox, the other one will be updated with the same value.
    • Sys.BindingMode.twoWay
      This is the default binding mode for input controls.
      <b>Name: </b><input id="name" type="text" value="{binding name, mode=twoWay}" />
      <b>Echo: </b><span id="nameDisplay">{binding name, mode=twoWay}</span>
      Figure: When you update either textbox, the other one will be updated with the same value.
    • Sys.BindingMode.oneWay 
      <b>Name: </b><input id="name" type="text" value="{binding name, mode=oneWay}" />
      <b>Echo: </b><span id="nameDisplay">{binding name, mode=twoWay}</span>
      Figure: When you update the Name, it won't affect the Echo.
    • Sys.BindingMode.oneWayToSource
      <b>Name: </b><input id="name" type="text" value="{binding name}" />
      <b>Echo: </b><span id="nameDisplay">{binding name, mode=oneWayToSource}</span>
      Figure: When you update the Name, it won't affect the Echo. But if you update Echo, it will affect the Name.
    • Sys.BindingMode.oneTime
      <b>Name: </b><input id="name" type="text" value="{binding name, mode=twoWay}" />
      <b>Echo: </b><span id="nameDisplay">{binding name, mode=oneTime}</span>
      Figure: When you update the Name in the first time, it will affect the Echo. After the first time, it won't affect the Echo.
    The live-binding syntax is similar to binding syntax in WPF (XAML).
  6. Do you allow users to comment and rate your pages?

    If you have published content on the internet, it's a good idea to allow your visitors to comment and rate your pages. Collecting feedback is a great way to make it easier to maintain your content. You can see which content is out of date, and which content is more highly regarded by your user base. This lets you focus on creating the most relevant content that you can. As well as providing you with feedback, allowing people to participate makes them feel more engaged with your content, broadening your reach.​

    There are a few ways that you can easily add comments an​​d interactivity, such as using widgets from:​

    ​The following video shows an overview of Yotpo ratings which we've implemented for our SSW Rules.

    Good Example: Yotpo ratings on the SSW Rules site​

  7. Do you always put JavaScript in a separate file?

    ASP.NET injects many lines during page rendering, so if you are using inline JavaScript, the line numbers will change during client side JavaScript debugging in VS.NET, FireBug or IE8 developer Tools.
    Figure: Bad Code - Using Inline JavaScript
    Figure: Bad Code - On PostBack Line numbers are changed for Inline JavaScript
    Figure: Good Code - Using JavaScript on Separate file ​

    So you should always put JavaScript in a separate file.  Then the line numbers will stay consistent during debugging. 
    Keeping JavaScript in a separate file is also good for production as it improves performance due to browser caching. 

    Note: During development, remember to hit CTRL-F5 to force the browser to re-fetch the files from the server or you may be debugging old version of the JavaScript file.

  8. Do you avoid using ASP/ASP.NET tags in plain HTML?

    ASP and ASP.NET tags have no place in plain HTML pages. They simply increase the size of the file and are ignored by browsers, because the need to be processed on the server. When converting ASP.NET pages to plain HTML you must be careful to remove all of these tags.​

    ​<%@ Page Language="C#" %>
    <ssw:inctop id="inctop" runat="server"></ssw:inctop>

    ​​​​​Figure: Bad Example - ASP.NET tags accidentaly placed in a plain HTML documents

    We have a program called SSW Code Auditor​ to check for this rule.

  9. Do you have generic exception handler in your Global.asax?

    Add your code to handle generic exception of your ASP.NET application in Application_Error.

    ​​private static readonly ILog log = LogManager.GetLogger(typeof(MvcApplication));

            protected void Application_Error(object sender, EventArgs e)
                Exception ex = Server.GetLastError().GetBaseException();
                log.Fatal("Unhandled Exception", ex);

    ​Figure. Exception handler in Global.asax.cs​
  10. Do you keep your "DataBinder.Eval" clean?

    Remember ASP code, you had lots of inline processing. Using DataBinder.Eval encourages the same tendencies. DataBinder.Eval is OK, so is formatting a number to a currency. But not formatting based on business rules. The general rule is, any code between <%# and DataBinder.Eval is bad and should be moved into protected method on the form.

    Here is a good and a bad way to binding fields in ASP.NET in a datagrid.

    Putting all the field binding code AND the business rule in the


    • Bad: Business logic is in the presentation layer (.aspx file)
    • Bad: No intellisense
    • Bad: Compile errors are not picked up 


    <asp:Label id="tumorSizeLabel" runat="server" Text='<%# iif( Container.DataItem.Row.IsNull("TumorSize"), "N/A",DataBinder.Eval(Container, "DataItem.TumorSize", "0.00")) %>'/>

    Bad code​​

    ​​Putting the code on the ItemDataBound Event.

    • Good: Business logic is in the code behind (.vb or .cs file)
    • Good: intellisense
    • Bad: Code Bloat
    • Bad: Have to use server control for all controls (viewstate bloat)

    In server page: 

    ​​<asp:Label id="tumorSizeLabel" runat="server" /> 

    In code behind:

    Private Sub patientDataGrid_ItemDataBound( ByVal sender As Object, ByVal e As DataGridItemEventArgs)_
    Handles patientDataGrid.ItemDataBound
    If( e.Item.ItemType = ListItemType.Item Or e.Item.ItemType = ListItemType.AlternatingItem) Then
    Dim tumorSizeLabel As Label = e.Item.FindControl("tumorSizeLabel")
    Dim rowView As DataRowView = CType(e.Item.DataItem, DataRowView)
    Dim row As PatientDataSet.PatientRow = CType(rowView.Row, PatientDataSet.PatientRow)
    If row.IsTumorSizeNull() Then
    tumorSizeLabel.Text = "N/A"
    tumorSizeLabel.Text = row.TumorSize.ToString("0.00")
    End If
    End If
    End Sub

    Good code​​

    ​​We have a program called SSW Code Auditor to check for this rule.​​​

  11. Do you keep your website loading time acceptable?

    Nobody Likes a Slow Website. You should optimize the performance of your websites so it loads as quick as possible.

    You should use Pingdom Website Speed Test​​​ to analyze the load speed of your websites and learn how to make them faster.

    Then work to k​eep it under 3 MB:

    • Unacceptable > 3 MB​​
    • OK 1.5 MB to 3 MB ( is 1.5MB)
    • Good < 1.5 MB​
    • Excellent < 1 MB
  12. Do you know not to use LinkButton?

    If we want to refresh and data bind the same page from client side, we can use the javascript function calls "__doPostBack". We shouldn't fire this post back in LinkButton. Otherwise, there will be an error.
    Figure: Right click the link with __doPostBack event  ​
    Figure: New window with incorrect URL

    <asp:Panel runat="server" ID="mUpdatePanel" OnLoad="mUpdatePanel_Load">
    <asp:Label runat="server" ID="lblTime" />
    <br />
    <asp:GridView ID="gvList" runat="server" AutoGenerateColumns="false">
    <asp:BoundField DataField="ID" HeaderText="ID" />
    <asp:BoundField DataField="Name" HeaderText="Name" />
    <br />
    ID:<asp:TextBox ID="txtID" runat="server"/>
    Name:<asp:TextBox ID="txtName" runat="server"/>
    protected void mUpdatePanel_Load(object sender, EventArgs e)
    lblTime.Text = DateTime.Now.ToLongTimeString();
    ArrayList mList = (ArrayList)ViewState["List"];
    if (txtName.Text.Length > 0)
    Client mClient = new Client();
    mClient.ID = Int32.Parse(txtID.Text);
    mClient.Name = txtName.Text;
    ViewState["List"] = mList;
    gvList.DataSource = mList;

    Sample Code​​​

    ​​​<a href="javascript:__doPostBack('mUpdatePanel','');">Refresh</a>

    Bad Code​

    <input type="button" onclick="javascript:__doPostBack('mUpdatePanel','');" value="Refresh" />

    Good Code​

    We have a program called SSW Code Auditor to check for this rule.​

  13. Do you know that or sections in web.config must contain a or a element?

    If web.config contains a <httpHandlers> or <httpModules> section, that section must contain a <remove... /> or a <clear /> element.

    This basically forces developers to explicitly enable inheritance in nested virtual directories. In 99% of cases this developers won't use inheritance on these two sections, however it causes issues when somebody wants to add a module or handler to the parent virtual directory.

             <add verb="*" 
             <add verb="GET,HEAD" 
    Figure: Bad example
             <add verb="*" 
             <add verb="GET,HEAD" 
    Figure: Good example
  14. Do you know the best sample applications?

    Before starting a software project and evaluating a new technology, it is important to know what the best practices are. The easiest way to get up and running is by looking at a sample application. Below are a list of sample applications that we’ve curated and given our seal of approval.

    SQL Server






  15. Do you know when anchor should "run at server"?

    <a> tag should runat=“server" *ONLY* if you need to change the target at runtime.

    If you include runat=“server" for an HTML element that you do not need access to in code behind, you are introducing a whole lot of overhead you do not need. ​

    ​We have a program called SSW Code Auditor to check for this rule.​​

  16. Do You Know Which Packages To Add To Your New MVC Project?

    ​​​When you create a new MVC project in Visual Studio it is important to include the right packages from the start. This makes the project more manageable and you become more efficient in producing your final result.

    ​If you add old, obsolete or incorrect NuGet packages, the project will suffer and you might have decreased performance or scope creep as new requirements are discovered. 

    Avoid old technologies such as:

    • ​​MVC Web Forms
    • KnockoutJS
    When you create a project you should be adding the following NuGet Packages:
    • SSW.DataOnion
    • SSW.HealthCheck
    • ​​AutoFac
    • Serilog

    You should also add the following NPM packages:

    • Angular JS
    • Bootstrap
    • Gulp

    Note: Prior to 2016, SSW recommend developers choose bower over NPM as their front end package manager. That recomendation has chan​ged due to the industry trend away from bower.


    Figure: NPM Popularity has been increasing

    Part of SugarLearning Developer Induction.

  17. Do you replace the 404 error with a useful error page?


    Error page, you say? You worked hard to make sure my site has no errors!! Well, surfers don't always type URLs accurately. No website is immune to such errors.

    A well-designed custom error page encourages surfers to remain in your site and help them to the right page. Although it's possible to redirect error codes straight to your homepage, that doesn't tell visitors what's going on. It's more user-friendly to explain that there was a problem and provide some alternatives. Supply a link to your home page or other links, or offer your site's search function if you have one. ​

    <customErrors mode="Off"></customErrors>

    Figure: This is the default code in the web.config

    <customErrors mode="RemoteOnly" defaultRedirect="/ssw/ErrorPage.aspx">
    <error statusCode="404" redirect="/ssw/SSWCustomError404.aspx">

    Figure: this is the current code in the web.config of the SSW Site 

    For ASP.NET website, the detailed information would be presented to the remote machines when an unhandled error occurs if the customErrors mode is off.

    This error information is useful for the developer to do debugging. However, it would leak out some confidential information which could be used to get into your system by the hackers. We can assume that if a SQL exception occurs by accident, which may expose database sensitive information (e.g. connection string; SQL script). So, to prevent these leaks, you should set the "mode" attribute of the tag <customerrors> to "RemoteOnly" or "On" in the web.config file and create a user-friendly customized error page to replace the detailed error information.

    <customErrors mode="RemoteOnly" defaultRedirect="GenericErrorPage.htm"></customErrors>

    Figure: Turning on "customErrors" protects sensitive information against Hacker 
    Figure: Bad example - Unhandled e rror
    Figure: Good example - Custom error page

    Related rule

  18. Do you use server side comments?

    ​Use server side comments:

    • Use <%-- Comment Here --%> instead of <!-- Comment Here --> (Does not get rendered to the client, saves us a few precious kilobytes)
    • Use CTRL + K, C to comment and CTRL + K, U to uncomment​
  19. Do you use the best Web UI libraries?

    ​Don't waste time evaluating which Web UI libraries to use. Most of the commonly used libraries are very similar in functionality . The recommend  library is Twitter Bootstrap.

    It's the most popular available framework today, which means more people involved in the project, more tutorials and articles from the community, more real-world examples/websites, more third-party extensions, and better integration with other​ web development products

    Figure: Bad example - Zurb Foundation is the second most popular, but it uses Sass files and​ has the worst name

    In VS 2013 Zurb Foundation was always out of date on Nuget. So if you use it (which is not recommended) download it direct from ​Github.​​ 

    In VS 2015 these packages were moved from N​uget to Bower. 

    Figure: Good example - leader among frameworks today, Bootstrap toolkit is recommended to build​ successful websites

    The 3 things a developer need to know to get up and running quickly with ASP.NET MVC


    Twitter Bootstrap & ASP.NET MVC ​​​​- Intro / Quickstart


    ​Other useful frameworks​

    Now that you saved a lot of UI develo​pment time by using Bootstrap, you can play around with other useful frameworks.​

    • KendoUI for enhanced HTML and jQuery controls
    • KnockoutJS for view-model data binding
    • SignalR for real-time web functionality​