The ASP.NET do and don’ts serie : episode 4 – If you retrieve server controls in your code-behind do it the safe way !

When we are developping with databound controls, a common action is to retreive controls (like dropdownlists) in an objectdatasource’s “Inserting” event.

Here is a specific example :

In the InsertItemTemplate of a ListView:


<asp:ObjectDataSource runat="server" ID="MyDataSource"
 // ... />

<asp:DropDownList runat="server"
       ID="MyDDL"
       DataSourceID="MyDataSource"
       DataTextField="TheText"
       DataValueField="TheValue"/>

Do:


protected void TheDataSource_Inserting(object sender, ObjectDataSourceMethodEventArgs e)
{
    if (MyListView.InsertItem == null)
       return;

     DropDownList myDDL= MyListView.InsertItem.FindControl("MyDDL") as DropDownList;
     if (myDDL== null)
         return;
     if (string.IsNullOrEmpty(myDDL.SelectedValue))
         return;

    e.InputParameters["TheWantedValue"] = myDDL.SelectedValue;
 }

Don’t:


protected void TheDataSource_Inserting(object sender, ObjectDataSourceMethodEventArgs e)
{
    e.InputParameters.Add("TheWantedValue", ((DropDownList)MyListView.InsertItem.FindControl("MyDDL")).SelectedValue);
}

This for an obvious reason : you can’t always be sure that a problem won’t pop up.

A random problem can occur anywhere, whether the dropdownlist population or something else

So, be safe and protect yourself !

Incoming search terms:

  • objectdatasourcemethodeventargs dropdownlist

The ASP.NET do and don’ts serie : episode 3 – use the validator designed for your needs !

This post is relative to the first episode of the “ASP.NET do and don’ts serie”

ASP.NET contains several validation controls. Be sure to use the good ones for your needs.

Imagine you have the following dropdownlist

<asp:DropDownList runat="server" ID="MyDDL"
      // datasource params
     AppendDataBoundItems="true">
     <asp:ListItem Text="select a value" Value="-1" Selected="True" />
</asp:DropDownList>

Do:


<asp:RequiredFieldValidator runat="server" ID="MyDDLValidator" ControlToValidate="MyDDL" ErrorMessage="Selection required" InitialValue="-1" />

Don’t:


<asp:CompareValidator runat="server" ID="MyDDLValidator"
 ValueToCompare="-1" ControlToValidate="MyDDL"
 Operator="NotEqual" ErrorMessage="Selection required" />

The ASP.NET do and don’ts serie : episode 2 – the navigation controls

There are many controls you can use for the navigation in ASP.NET.

Be sure that you use the good ones for the good uses.

Let say we want a link on a page to redirect on an other page

Do:

in the aspx markup


<asp:HyperLink runat="server" ID="NavigateToOtherPage" NavigateUrl="~/otherpage.aspx" Text="Go to the other page" />

or even better if you just want to redirect on a page


<a href="otherpage.aspx">Go to the other page</a>

Don”t:

in the aspx markup


<asp:LinkButton runat="server" ID="NavigateToOtherPage" Text="Go to the other page" onclick="RedirectToOtherPage" />

and in the code behind


protected void RedirectToOtherPage(object sender, EventArgs e)
{
     Response.Redirect("~/otherpage.aspx");
}

The ASP.NET do and don’ts serie : episode 1 – the custom validator control

This is the first post of a serie on the ASP.NET practices.

For this serie, I get inspiration from what I see in my daily work or on the web

Don’t use custom validator when you can use an other control !

Do:

in the aspx markup


<asp:TextBox runat="server" ID="FeedURLTbx"  />

<asp:RegularExpressionValidator runat="server"
     ID="URLFormatValidator"
     ControlToValidate="FeedURLTbx"
     ValidationExpression="(http|ftp|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&amp;:/~\+#]*[\w\-\@?^=%&amp;/~\+#])?"
     Text="!"
     ErrorMessage="The URL format is not valid." />

Don’t:

in the aspx markup


<asp:TextBox runat="server" ID="FeedURLTbx"  />

 <asp:CustomValidator runat="server" ID="URLFormatValidator"
 ControlToValidate="FeedURLTbx"
 ErrorMessage="The URL format is not valid."
 OnServerValidate="ValidateURL" />

and in the aspx code behind

protected void ValidateURL(object source, ServerValidateEventArgs args)
{

System.Text.RegularExpressions.Regex myRegExp = new  System.Text.RegularExpressions.Regex(@"(http|ftp|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&amp;:/~\+#]*[\w\-\@?^=%&amp;/~\+#])?");

args.IsValid = myRegExp.IsMatch(args.Value);
}

Why??

First because the RegularExpressionValidator is designed for string validations and it’s a non sense to do the same with another control !

Second because the CustomValidator used like here will cause a postback while the RegularExpressionValidator will generate the validation javascript and don’t cause postback.

With the RegularExpressionValidator :
good_start
good_end

With the CustomValidator :

bad_start
bad_end

I think the first reason is enough to not discuss the point !