Highlight selected row in ASP.NET MVC: it’s about requirements

This is more a view from a different angle than a technically post: suppose you have an ASP.NET MVC application with a simple table with products (let’s name the view Products). Clicking on any product “Details” link, you should see the same table but with the product clicked previously highlighted and the product details.

How would you implement such a simple requirement? Highlight a row.

Well, my answer is “depends”. Depends how it is asked.
    1. Clear requirement: If the highlight stuff is part of an iteration, is a clear requirement (perhaps your Team Foundation Server check in policy will not allow to check in that fix without specify the test which cover it) then I would do it like this:

public partial class Product
{        public bool Selected
         {
              get;
              set;
         }
}

Add the Selected property in the partial class definition (Product is a Linq2Sql or a Entity Framework entity). You can use also a ViewModel if your page is more complex (and same thing applies, add a new property to the ViewModel).

Then your controller can look like this (just a guideline, don’t use it exactly like this!):

public ActionResult MyProductList(int? productID)
{
    List<Product> products = m_service.FindProducts();
    products.Find(p => p.ProductID == productID).FirstOrDefault().Selected = true;
    return View(products);
}

That is easy testable and you can mark your work item as done and associating with a simple test.

    2. UI Layout or other sources (like an angry email from the project manager): You just have the UI layout from a web designer and there the selected row is highlighted. That simple “spaghetti” code is more than enough:

<% RouteValueDictionary  tRVD = new RouteValueDictionary(ViewContext.RouteData.Values); %>
      <table width="100%">
        <% foreach (var product in Model) { %>
            <tr <% if (product.ProductID.ToString() == tRVD["productID"]) { %>
                class="selected" <% } %>>
                     <td width="80%">
                        <%= Html.ActionLink(product.Name,
                         "Edit", new { id = product.ProductID })%>
                </td>
...

How would you handle case 1 in the proper way?

emipasat posted at 2009-9-21 Category: Development/Programming | Tags: ,

Leave a Reply

(Ctrl + Enter)