.NET Performance Blog

July 25, 2009

ASP.NET MVC Grid – Part 7 – Reusable control

Filed under: ASP.NET MVC — Eric P @ 10:53 am

At this point all the features I planned in Part 1 have been implemented. It is time to make grid re-usable.

Click on image to view the whole screenshot

Click on image to view the whole screenshot

You can see demo here:
http://samples.entechsolutions.com/MvcGridSample/Part7

Code is available here:
http://samples.entechsolutions.com/Downloads/MvcGridSample/MvcGridSample_Part7.zip


So how does one make a grid into reusable control. There is no standard approach in MVC to separate both Logic and Presentation, similar to User Controls in web forms. I hope one will be provided in MVC 2, but for now it is up to a developer to pick from several options.

A found a good article on consolidating HTML for re-usability here: http://www.ajaxprojects.com/ajax/tutorialdetails.php?itemid=487#start. It includes various approaches and strengths and weaknesses of each one.

I considered the following options that would allow me to separate both Grid logic and UI.

a. Extending HtmlHelper

An example of using HtmlHelper to generate a simple pager is here: http://blogs.taiga.nl/martijn/?s=pager
I think helpers are to be better left for building very small HTML pieces, like action links. Even a pager in the example above may be too complex for HtmlHelper.

b. RenderAction

This was mentioned by Rob Connery here:
http://blog.wekeroad.com/blog/asp-net-mvc-preview-4-componentcontroller-is-now-renderaction/

This approach mimics User Control in WebForms, but instead of code behind – you need provide a separate controller to handle Grid Actions. There are some reservations to using this approach described here:
http://haacked.com/archive/2008/07/16/aspnetmvc-codeplex-preview4.aspx

Some people comment that this is not a “Valid” MVC approach, since view would have knowledge of Controllers.

This approach works best for controls like Login form which exist on multiple pages or master page, but the functionality is always the same. In case of the Grid control – the functionality will be custom depending on the entity being desplayed, so RenderAction doesn’t exactly fit here (even though it could work).

c. Partial views
In this approach partial views are used to encapsulate common HTML. All the logic goes into the parent controller. This approach may be the best option for now.


Implementation

The first thing to do to make control re-usable is “Find What Is Varying and Encapsulate It”. The simplest way to do that is to create another grid for a different entity. Then look for code duplication and encapsulate it into shared views/classes.

Add Product Entity

I created a new Product entity that looks like this:


public class Product
{
	[Required(ErrorMessage = "Required.")]
	public int ID { get; set; }

	[Required(ErrorMessage = "Required.")]
	public string Name { get; set; }

	[Required(ErrorMessage = "Required.")]
	[StringLength(10, ErrorMessage = "Must be 10 characters.", MinimumLength = 10)]
	public string SKU { get; set; }

	public string Description { get; set; }

	[Required(ErrorMessage = "Required.")]
    public decimal Price { get; set; }
}

Then I created ProductService class, ProductController and all the Views to List and Edit products

\Models
     Product.cs
     ProductService.cs -  Add/Update/GetByID for product

\Controllers
     ProductController.cs

\Views
    \Product
        List.aspx
        Edit.aspx
        _Grid.aspx

Finding what varies

In Each Grid – the following pieces will work and look the same:

  • Keyword Search and switching search modes
  • Pager navigation and size
  • Sorter
  • CSS and JS

Mvc_Grid_SamePieces
And the following pieces will vary:

  • Column and row data in grid table
  • Advanced Search form

Mvc_Grid_VariedPieces

Here is the screen shot of product list for comparison
Mvc_Grid_Products_List

Extracting Partial views

To incapsulate common UI, while allowing users to only implement pieces that vary I separated Grid html into 4 partials:

_Grid.aspx – generic grid display
_SearchForm.aspx – generic search form
_GridData.aspx – custom display of Grid Data
_AdvancedSearchForm.aspx – custom advanced search form

The Views directory structure looks like:


\Views
    \Customer
        List.aspx  - includes RenderPartial for _Grid and _SearchForm in /Views/Shared
        Edit.aspx
        _GridData.aspx - data table for displaying Customer entries
        _AdvancedSearchForm.aspx - avanced search fields to find Customers
    
    \Product
        List.aspx
        Edit.aspx
        _GridData.aspx - data table for displaying Product entries
        _AdvancedSearchForm.aspx - avanced search fields to find Products

    \Shared
        _Grid.aspx 
             - generic grid display - that provide Grid structure with header and paging, 
                but leaves it up to custom  _GridData (for ex. in \Views\Customer) to display columns and rows
        _SearchForm.aspx 
             - generic search form with Keyword search and link to switch to Advanced.  For custom Advanced Search it 
               will use _AdvancedSearchForm located in appropriate Views directory like (Views\Customer) 
        _Pager.aspx -  to be able to repeat pager on top and bottom of the grid

Passing view models

To be able to pass information from \Customer\List.aspx to \Shared\_Grid.asmx and then back to \Customer\_GridData.aspx – I created an interface that would allow me to box and un-box grid data. I extracted IGrid interface from Grid and passed to shared views:

public interface IGrid
{
	Pager Pager { get; set; }
	Sorter Sorter { get; set; }
	GridAction GridAction { get; set; }
	bool IsEmpty { get; }
	SelectList PageSizeSelectList();
	string PageNavActionLink(string linkText, int page);
	string SortActionLink(string linkText, string sortField);
}

Here is the whole workflow:

a. Customer\List.aspx renders two partial views “_SearchForm.aspx” and “_Grid.aspx”

<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<CustomerGrid>" %>
...
<div id="search-form">
	<% Html.RenderPartial("_SearchForm", Model.SearchForm); %>
</div> <!-- search-form -->
	
<div style="clear: both"></div>
		
<div id="grid">
	<% Html.RenderPartial("_Grid", Model); %>
</div>  <!-- grid -->	
...

b. _Grid.aspx takes IGrid as ViewModel and passes it on to \Shared\_Pager.ascx and \Customer\_GridData.ascx

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<IGrid>" %>
...
<div class="pager-nav">			
	<% Html.RenderPartial("_PagerNav", Model); %>
</div>
...
<div id="grid-data">
	<% Html.RenderPartial("_GridData", Model); %>
</div> <!-- data -->
...

c. Partial Customer\_GridData.ascx automatically unboxes IGrid into CustomerGrid

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<CustomerGrid>" %>
...

d. Move the search logic outside of controllers

When going through ProductController and CustomerController code – I noticed that both contained a lot of LINQ search logic. For better separation of concerns, I moved the search logic into Model/Domain classes: CustomerCriteria and ProductCriteria. This leaves controllers to do what they do best: display logic.


Observations

Conclusion and what is next…

In this part, I was able to re-use the Grid for both Customers and Products by moving all the common functionality into shared partial views.

There is still a bit of code that needs to go into the Controller to fill Grid data and save/load grid state. I was thinking of moving this code into base controller class, but this could introduce some coupling. I would like to see if RenderAction may be a better solution.

In the near future I will be using Grid control in several client projects. That will be a great opportunity to smooth out any rough edges. I also plan to introduce some of the more advanced features like: Batch Actions with check boxes, multi-column sorting and inline editing. So stay tuned…

In the near future I will add the following bug fixes/enhancements:
1. Use namespace for Grid’s javascript to provide for a better encapsulation
2. Fix a bug where user can’t switch to advanced search if JS is disabled
3. Fix a bug where server side errors are not displayed for Advanced Search, when date or numeric fields are invalid
4. Introduce unit tests for grid actions (other then Paging which already has unit tests)
5. CSS Bug fix: There is a white dot that appears in FireFox right under header row.

Advertisements

July 17, 2009

ASP.NET MVC Grid – Part 6 – Advanced Search, AJAX, Users with Javascript Disabled

Filed under: ASP.NET MVC — Eric P @ 8:06 am

In this part I will implement:

  • advanced search
  • using AJAX for grid actions
  • support for users with Javascript disabled
  • separate grid.css and grid.js

Click image to view the full screenshot

Click image to view the full screenshot


You can see demo here:
http://samples.entechsolutions.com/MvcGridSample/Part6

Code is available here:
http://samples.entechsolutions.com/Downloads/MvcGridSample/MvcGridSample_Part6.zip

Implementation

1. Advanced Search
Advanced Search differs from Keyword Search in a way that users can search for customers using one or more fields, for example – find all customers with first name “John” and with last order placed in the last month.

To implement advanced search I extended SearchForm class to include fields like First Name, Last Name, Phone, etc…


public class SearchForm
{
	//Properties
	public bool IsAdvanced { get; set; }
	public string Keyword { get; set; }
}

public class CustomerSearchForm : SearchForm
{
	public string FirstName { get; set; }
	public string LastName { get; set; }
	public string Email { get; set; }
	public string Phone { get; set; }

	public DateTime? FromDateOfLastOrder { get; set; }
	public DateTime? ToDateOfLastOrder { get; set; }
}

To be able to access Advanced search fields in View through a model, I passed CustomerSearchForm as generic when declaring grid:



public class CustomerController : Controller
{
        private Grid<Customer, CustomerSearchForm> _grid;
        ...
}

public class Grid<TEntity, TSearchForm> where  TSearchForm : SearchForm, new()
{
	private Pager _pager;
	private Sorter _sorter;
	private TSearchForm _searchForm;
    
   

This way I could use:

<td>
	First Name<br />
	<%= Html.TextBox("SearchForm.FirstName", null, new { @style = "width: 100px", @maxlength = "20" })%>
</td>

otherwise binder had issue binding to correct properties.

Then I added some animation with help of JQuery – to switch between Keyword and Advanced searches. See more about this in “Observations” section.

2. AJAX for Grid Actions
This functionality was very easy to implement in Web Forms. You just had to put UpdatePanel around the GridView and all paging and sorting would be asynchronous.

In MVC, it is a little more complicated, but with a benefit of a more control and flexibility. I moved Grid html (without search form) into a partial class “_Grid.aspx”. Then I used JQuery AJAX functionality and BlockUI plugin to perform all page actions without refreshing the whole page.


jQuery(document).ready(function() {

	initGrid();

 	//Intercept form submit and do submission with AJAX
	$("#grid").parents("form:first").submit(function() {
		submitFormWithAjax();
		return false;
	});
...
}); 


function submitFormWithAjax() {

	var form = $("#grid").parents("form:first");
	var formData= form.serialize();         //Serialize form control values to be passed asynchronously

	block();   //use BlockUI to display "Processing ... " popup

	$.ajax({
		type: "POST",
		url: "_Grid",           //Partial view
		data: formData,
		success: function(newHtml) {
			//Use timeout of half a second to see "Processing..." animation, otherwise it goes by too quickly.
			setTimeout(function() {
							$("#grid").html(newHtml);
	
							initGrid();
							unblock(); }, 500);
		},

		error: function(request, textStatus, errorThrown) {
			alert("AJAX error: " + request.statusText);
			unblock();
		}
	});
}

function block() {
	$('#grid #grid-data').block({
		message: '<div class="blockUI-message">Processing...</div>',
		css: { border: 'none', width: 'auto' },
		overlayCSS: { backgroundColor: '#C0C0C0' }
	});
}

function unblock() {
	$('#grid #grid-data').unblock();
}

3. Support for users with javascript disabled
This feature allows users with Javascript disabled to use most of the Grid’s functionality. Surprisingly, there are still 5% of users who have JS disabled for variety of reasons (http://www.w3schools.com/browsers/browsers_stats.asp).

For Paging and Sorting, I previously submitted the form using javascript, so the links would look like:

//paging
<a href="#" onclick="goToPage(2)">&gt;</a> 


//sorting
<th>
	<a href="#" class="" onclick="sort('FirstName', 'Asc');">First Name</a>
</th>

//with javascript used to set appropriate hidden variables and grid action, then submit the form
function goToPage(pageIndex) {
	$("#Pager_CurrentPage").val(pageIndex);
	$("#GridAction").val("GoToPage");

	submitForm();
}

function sort(sortField, sortDirection) {
	$("#GridAction").val("Sort");
	
	$("#Sorter_SortField").val(sortField);
	$("#Sorter_SortDirection").val(sortDirection);

	submitForm();
}

For this to work with JS disabled, i replaced “#” in href attribute with a url containing the whole grid state as well as appropriate paging/sorting action. So now, paging and sorting links look like:


//Paging
<a href="/Customer/List?Pager.CurrentPage=2&Pager.PageSize=5&Sorter.SortField=ID&Sorter.SortDirection=Asc&SearchForm.IsAdvanced=False&SearchForm.Keyword=&GridAction=GoToPage" onclick="goToPage(2); return false;">&gt;</a>

//Sorting
<a class="" href="/Customer/List?Pager.CurrentPage=1&Pager.PageSize=5&Sorter.SortField=FirstName&Sorter.SortDirection=Asc&SearchForm.IsAdvanced=False&SearchForm.Keyword=&GridAction=Sort" onclick="sort('FirstName', 'Asc'); return false;">First Name</a>

Notice that onclick now has a “return false;” statement. This suppresses default link action – which is to go to URL specified in HREF.

Internally this is implemented using Grid.GetQueryString and Grid.GenUrl methods, that are called from methods used to generate links – Grid.PageNavActionLink(…) and Grid.SortActionLink(…).

One nice side-effect from using this approach is that a Search Engine crawler like Google crawler should be able to crawl all the data in the grid using page/sort URLs.

For Page Size, I added “Refresh” button which is only displayed if JS is disabled:

<noscript><input type="submit" id="refresh-button" value="refresh" /></noscript>

One feature that doesn’t work yet for “JS disabled” mode is switching Search to Advanced Form. I will get it to work in next part.

4. Separate grid.js and grid.css
It is usually a bad practice to keep big chunks of javascript and CSS inline on the actual page. To correct this issue, I moved all grid javascript and styles into separate files.

JS is now in ‘/Scripts/grid.js’.
CSS is now in ‘/Content/grid.css’.

This will also help with re-usability.

Observations

  • When adding conditions for Advanced search I discovered that C# String.Contains method doesn’t have an option for case-insensitive comparison. To do that I added string extensions from the following link:
    http://schleichermann.wordpress.com/2009/02/24/c-stringcontains-case-insensitive-extension-method/

    public static class StringExtensions
    {
    	public static bool Contains(this String source, String value, StringComparison comparison)
    	{
    		return source.IndexOf(value, comparison) != -1;
    	}
        
    	public static bool ContainsCaseInsensitive(this String source, String value)
    	{
    		return Contains(source, value, StringComparison.CurrentCultureIgnoreCase);
    	}
    }
    
  • When I worked on animation for hiding/showing advanced search, I noticed that animations ran asynchronously, so sometimes it would fully skip the first animation if the second animation was called right away.

    Originally the code looked like this:

    $("#search-form #advanced-link").click(function() {
    
    	//Hide keyword search form using slide up animation
    	$("#search-form").slideUp("medium");
    
    	//Hide/show appropriate links and form fields
    	...
    	
    	//Display advanced search form using slide down animation
    	$("#search-form").slideDown("medium");
    
    	...
    });
    

    Since slideUp was asynchronous, slideDown would get called even before slideUp would get started, so all I would see was the Keyword form disappearing (without animation) and Advanced search appearing with animation.

    To make sure that slideUp animation finished before calling slideDown – I changed the code to call slideDown in slideUp’s callback argument. Final code looks like this:

    $("#search-form #advanced-link").click(function() {
    	$("#search-form").slideUp("medium", function() {
    		...
    		$("#search-form").slideDown("medium");
    	});
    
    	...
    });
    

Coming up…

Next will be the biggest task of them all. Making grid into re-usable control…

July 10, 2009

ASP.NET MVC Grid – Part 5 – Persisting Grid State

Filed under: ASP.NET MVC,General — Eric P @ 8:14 am

In this part I will implement the following items:

  • persist the state of the grid
  • update UI with row striping and row click actions
  • handle a “last customer on page” edge case
  • add status/notifications line when customer is added/deleted/modified
  • validate edit form
Click on the image to view the whole screenshot.

Click on the image to view the whole screenshot.

You can see demo here:
http://samples.entechsolutions.com/MvcGridSample/Part5

Code is available here:
http://samples.entechsolutions.com/Downloads/MvcGridSample/MvcGridSample_Part5.zip

Implementation

1. Persist state of the grid
A common use case for any grid control – is remembering the state of the grid when user comes back to the list page. So if grid is currently on page 2 and sorted by phone and user clicks on Edit – then saves customer and goes back to grid – the grid will still be on page 2 and sorted by phone.

To implement this functionality I created a new service class GridStateService with methods
Save(key, Grid)
Grid Load(key)
bool Exists(key);

This service uses session to save/load grid’s state, so while the person is using the site and his/her session hasn’t expired, the grid state (current page, page size, etc…) persists. If needed, it should be simple to change the persistence mechanism to store grid state in the cookie or the database. In those cases, whenever user would come back to the site, his/her last preferences (like sorting by “Phone” or page-size=50) would remain.

Here is how GridStateService is used in CustomerController.List:


[AcceptVerbs(HttpVerbs.Get)]
public ActionResult List()
{
	string key = GetGridKey();   //This function returns current url used to uniquely identify the grid
	if (_gridStateService.Exists(key))
	{
		_grid = _gridStateService.Load(key);
	}
	else
	{
		_grid = new Grid<Customer>
					(
						new Pager {CurrentPage = 1, PageSize = 5}, 
						new Sorter("ID", SortDirection.Asc)
					);
	}

	UpdateGridData();

	return View(_grid);
}

Here is the code the saves last state of the grid.


[AcceptVerbs(HttpVerbs.Post)]
public ActionResult List(Grid<Customer> grid)
{
	_grid = grid;

	_grid.ProcessAction();

	UpdateGridData();

        //Check if there is data in the grid
	if (_grid.Data.Count() > 0)
		SaveGridState();
	
	return View(_grid);
}

private void SaveGridState()
{
	string key = GetGridKey();
	_gridStateService.Save(key, _grid);
}

2.Row striping and row click

The row striping and highlighting (which allows for better readability) was implemented using approach described in the following article:
http://webdevdotnet.blogspot.com/2009/06/aspnet-mvc-jquery-part-2-zebra-striping.html

As for row-clicking – I added onlcick handler to data row’s tr tag:

<tr onclick="onRowClick(<%= item.ID %>)">
     <td>

When user clicks on the row they will be taken to customer edit screen. This is handled by JS function:

function onRowClick(id) {
	document.location = "/Customer/Edit/" + id;
}

3. Edge case for deleting last customer on the page

If I am using 5 rows per page with 6 customers and I deleted sixth customer on the second page, the grid should automatically switch to page 1 instead of showing page 2 with no customers.

This condition was handled in pager using the following code:

//handle a case when user deleted all rows on last page
if (_currentPage > _totalPages)
    _currentPage = _totalPages;

4. Status line when customer is added/deleted/modified

This functionality is related to operations triggered in the grid page.
Previously, if I deleted a customer there would be no indication that customer was deleted. The grid would get refreshed, but there would be no explicit notification that customer was actually deleted.

I used TempData functionality on the MasterPage to display such messages/notifications. All operations, add/edit/delete, that are successfully performed on the customer are now followed by a status line message (yellow box) on the grid page.
This message fades out after 5 seconds (ain’t JQuery great).

5. Validate add/edit form
This functionality is not really grid-related, but I thought it would be important to have it for sample completeness. It is not very realistic to add a customer with all fields empty. It will also help when I implement inline editing.

I used Data Annonations approach described here:
http://www.asp.net/learn/mvc/tutorial-39-cs.aspx

I update UI a little to display error message right next to the input fields which are invalid.

Observations

  • Data annotations has a property DataType which takes DataType enumeation consisting of members like “Currency”, “Email Address”, etc… I originally thought it would validate my fields according to the type I pass, but that doesn’t work. But it doesn’t work this way. In one of the comments to article http://www.aspworkshops.com/blog/archive/2008/09/10/asp-net-mvc-tip-43-use-data-annotation-validators.aspx it states:

    The DataType attribute are not validators.
    So DataType(DataType.Email) will not validate a string for being an email address. These are ui type hint sttributes.

    GRRRRRRReat… I guess I will need a reg expression validator or custom validator for Email/Phone validations.

  • When messing with Data Annotations, I discovered another error. Even though it worked ok when binding simple models, I started getting NullReferenceException when binding to complex models (with sub objects). I discovered the fix here:

    http://stackoverflow.com/questions/820468/how-does-dataannotationsmodelbinder-work-with-custom-viewmodels

  • One more thing related to validation. Looks like there is no way to provide custom error messages for data type conversions during binding. So if user enters some text into “Orders Placed” field – the error message is always:

    The value ‘SOME VALUE’ is not valid for the Orders Placed field.

    This is confirmed by Scott Gu in one of the comments to the following article:
    http://weblogs.asp.net/scottgu/archive/2008/09/02/asp-net-mvc-preview-5-and-form-posting-scenarios.aspx

    # re: ASP.NET MVC Preview 5 and Form Posting Scenarios
    Wednesday, September 03, 2008 11:39 PM by ScottGu

    Hi Florian,

    >>>>>>> I very much like the approach, cannot wait until this stuff is baked. One question – is there a way to intercept input validation and specify custom ErrorMessages?

    >>>>>>> E.g. in your example where the user enters a random string instead of the decimal number required by the model field you’re auto-generating an error message (‘.. invalid value ..’).

    >>>>>>> Is there a way to customize (and localize) this message, without inspecting and changing ModelState explicitely?

    Unfortunately with Preview 5 you need to manipulate the ModelState dictionary directly to enable this (either that or override the ModelBinder behavior to customize your own message).

    Hope this helps,

    Scott

    NOTE TO SELF: Add custom binder with a way to override type conversion error message.

Coming up…

There are a couple of items left before I will make the grid generic and re-usable. For the next part I will work on:

  • Making grid work if Javascript is disabled. This was brought to my attention by a comment in Part 3. Thank you, sironfoot.
  • Advandced search form – which will include fields “First Name”, “Last Name”, “Email”, date range for “Date of Last Order”, etc…
  • AJAX implementation so the whole page doesn’t refresh. Will work similar to how GridView worked in ASP.NET web forms if you put UpdatePanel around it.

July 6, 2009

ASP.NET MVC Grid – Part 4 – View Models, Unit Testing, Keyword Search

Filed under: ASP.NET MVC,General — Eric P @ 12:00 am

In this part, I decided to take a step back and do some refactoring. At the same time I would like to keep moving forward, by adding new Keyword Search functionality as well as an Auto Complete control to quickly find/edit a customer.

Click image to view full screenshot

Click image to view full screenshot

You can see demo here:
http://samples.entechsolutions.com/MvcGridSample/Part4

Code is available here:
http://samples.entechsolutions.com/Downloads/MvcGridSample/MvcGridSample_Part4.zip

Implementation

1. Use View Model (instead of ViewData) to organize Grid variables

As I mentioned in last couple of posts, ViewData was being used for too many variables. Such variables in ViewData are not strongly typed and result in verbose code which could be error-prone (for example null errors).

Instead I introduce the following class structure for Grid View Model:

class Grid
{
	Pager
		CurrentPage
		TotalPages
		RowStats
		...

	Sorter 
		SortField
		SortDirection


	SearchCriteria	- new functionality for keyword search
		Keyword


	GridAction - enumeration with items like "Sort", "GoToPage", ...
}

Using this class feels a lot cleaner then ViewData. In the code below Model is of class Grid.

<div id="gridHeader">
			<table>
				<tr>
					<td id="rowStats">
						<%= Model.Pager.RowStats %>
					</td>
					
					<td id="pagerNav">			
						<% if (Model.Pager.IsNavVisible) { %>
							<table>
								<tr>
									<td>
										<% if (Model.Pager.IsFirstPage) { %>
											<span class="disabled">&lt;&lt;</span>
										<% } else { %>
											<a href="#" onclick="goToPage(<%= Model.Pager.FirstPage %>)">&lt;&lt;</a>  
										<% } %>
									</td>
...

2. Write unit tests for pager. When creating a Pager class, I decided to follow TDD methodology and wrote unit tests first. Through this approach I discovered a lot of errors before actually integrating Pager into UI.

Here is a couple of unit tests… That check cases when Pager navigation should be visible and not visible.

namespace MvcGridSample.Tests.ViewModels.Shared
{
	[TestClass]
	public class PagerTest
	{

	       [TestMethod]
		public void Nav_Not_Visible_If_One_Page()
		{
			var pager = CreateAndInitPager(1, 10, 5);
			Assert.IsFalse(pager.IsNavVisible);
		}


		[TestMethod]
		public void Nav_Visible_If_More_Then_One_Page()
		{
			var pager = CreateAndInitPager(1, 10, 15);
			Assert.IsTrue(pager.IsNavVisible);

		}
               ...

3. Add Keyword search. This functionality allows user to search data by keyword which is matched against First Name, Last Name, Email or Phone. It can be expanded to search through other fields too (for ex. Customer Address – if one would exist).

The keyword search criteria was added to LINQ query using the following code:

private IQueryable<Customer> AddQuerySearchCriteria(IQueryable<Customer> query, SearchCriteria searchCriteria)
{
	if (!String.IsNullOrEmpty(searchCriteria.Keyword))
	{
		string keyword = searchCriteria.Keyword.ToLower();
		query = query.Where(customer => customer.FirstName.ToLower().Contains(keyword)
		                                || customer.LastName.ToLower().Contains(keyword)
						|| (customer.Email != null && customer.Email.Contains(keyword))
						|| (customer.Phone != null &&  customer.Phone.Contains(keyword)));
	}

	return query;
}

Note that I had to ensure that Email and Phone were not null, before checking them against keyword. Otherwise there were some “object reference is null” exceptions.

4. Add Auto Complete on Keyword. This is for a common use case when you would like to quickly find a record and perform certain operation on it. To try it out – start typing name of existing customer in keyword box. After first couple of letters you will see auto-complete drop down with a list of matching customers (by first name and last name).

If you select the customer in the list and click enter or click on it with a mouse – you will be taken to Edit Customer page.

To implement this functionality I used a JQuery auto-complete plugin from here:
http://docs.jquery.com/Plugins/Autocomplete

For this to work I created a method on controller that would return list of customer names in JSON format:

public ActionResult GetKeywordAutoCompleteData(string q, int limit)
{
	string keyword = q;

	IQueryable<Customer> query = _customerService.GetQueryable();
	query = query.Where(customer => customer.FirstName.ToLower().StartsWith(keyword)
	                                || customer.LastName.ToLower().StartsWith(keyword))
					.Take(10)
					.OrderBy(customer => customer.FirstName)
					.ThenBy(customer => customer.LastName);

	var list = query.Select(customer => new { 
												customer.ID, 
												Name = customer.FirstName + " " + customer.LastName});

	return Json(list);
}

Then call this method from client side using JQuery auto-complete plugin functionality:

jQuery(document).ready(function() {

	$("#SearchCriteria_Keyword").autocomplete(
		"/Customer/GetKeywordAutoCompleteData",
        {
        	dataType: 'json',
        	parse: function(data) {
        		var rows = new Array();

        		for (var i = 0; i < data.length; i++) {
        			rows&#91;i&#93; = { data: data&#91;i&#93;, value: data&#91;i&#93;.Name, result: data&#91;i&#93;.Name };
        		}
        		return rows;
        	},
        	formatItem: function(row, i, n) {
        		return row.Name;
        	},
        	width: 260,
        	selectFirst: false
        }
    );
    ....
&#91;/sourcecode&#93;


<h3>Observations</h3>
<ul>

<li>
         When HtmlHelper functions generate HTML controls - control IDs replace character  "." with "_".  For ex, if I want to use the following control in Jquery:


     <%= Html.Hidden("Sorter.SortDirection")%>

I need to call it like this:

     $("#Sorter_SortDirection").val(someVal);
  • Coming from Web Forms world, it seemed natural to me to create /App_Code directory to put all the utility classes.
    It has been working fine till now, but all of a sudden I started receiving compilation error:

    Compiler Error Message: CS0433: The type ‘MvcGridSample.StringFormatter’ exists in both ‘c:\Windows\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files\root\752a9979\7f1c3889\assembly\dl3\da179bc1\70581e2e_8ff9c901\MvcGridSample.DLL’ and ‘c:\Windows\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files\root\752a9979\7f1c3889\App_Code.nzexrw9-.dll’

    The reason for this issue is explained on the following page:
    http://weblogs.asp.net/meligy/archive/2008/08/03/converting-vs-2008-website-to-web-application.aspx

    During the conversion, VS 2008 renames your “App_Code” to “Old_App_Code”. This new name sounds ugly, but DO NOT RENAME IT BACK. In the “web application” model, all code will be in one assembly. In runtime, the web server does not know what web project type you are using. It does take all code in “App_Code” folder and create a new assembly for it. This way, if you have code in folder named “App_Code”, you’ll end up with RUNTIME compilation errors that the same types exist in two assemblies, the one created by VS, and the one created by IIS / ASP.NET Development Server.

    So to fix the issue I renamed the folder to “App_Code_”

  • Coming up for part 5…

    In part 5, I will implement grid persistance. Currently, if I am on page 3 of the grid sorted by phone number and I click on “Edit” next to one of the customers – when I save the customer and go back to grid – the grid returns to its default state of Page 1 and sorted by ID.

    Grid persistence – will remember the state of the grid when user goes to another page, so that when user will come back to the page with the grid, it will be in the state that it was left in.

    I will also add more JQuery functionality to format alternative rows, change row color on hover and provide “status line” notifications of user actions like created new customer, deleted customer, etc….

    July 1, 2009

    ASP.NET MVC Grid – Part 3 – Sorting

    Filed under: ASP.NET MVC — Eric P @ 11:57 am

    For this part I implemented server side sorting.

    screenshot

    click image to see full screenshot

    You can see demo here:
    http://samples.entechsolutions.com/MvcGridSample/Part3

    Code is available here:
    http://samples.entechsolutions.com/Downloads/MvcGridSample/MvcGridSample_Part3.zip

    Implementation

    1. Started by adding sort links for ID column

    	<th>
    	     ID
    	     <a href="#" onclick="sort('id', 'asc');">asc</a>
    	     <a href="#" onclick="sort('id', 'desc');">desc</a>
    	</th>
    

    2. Added javascript and hidden fields to pass sorting information to controller

    	<script type="text/javascript">
     	 	...
    
    		function sort(sortField, sortDirection) {
    			$("#gridAction").val("Sorted");
    			
    			$("#sortField").val(sortField);
    			$("#sortDirection").val(sortDirection);
    
    			submitForm();
    		}    
    				
    		function submitForm() {
    			var form = $("#grid").parents("form:first");
    			form.submit();
    		}            
    	</script> 
     	
    ...
    
    <%= Html.Hidden("sortField") %>
    <%= Html.Hidden("sortDirection") %>
    
    

    3. Modified CustomerController to handle sorting

    [AcceptVerbs(HttpVerbs.Post)]
    public ActionResult List(int currentPage, int pageSize, string sortField, string sortDirection, string gridAction)
    {
    	if (gridAction == "PageSizeChanged" || gridAction == "Sorted")  //Resetting currentPage on Sorted action
    		currentPage = 1;
    
    	IQueryable<Customer> query = _customerService.GetQueryable();
    	int totalRows = query.Count();
    	if (totalRows==0)
    		return View(new List<Customer>());
    
    	//Update query with order by clause
    	if (!String.IsNullOrEmpty(sortField))
    		query = AddQuerySorting(query, sortField, sortDirection);
    
    	int totalPages = (int)Math.Ceiling((double)totalRows / (double)pageSize);
    	if (totalPages != 1)
    		query = AddQueryPaging(query, pageSize, currentPage);
        
    	//Update ViewData with new sort params
    	UpdateSorterViewData(sortField, sortDirection);
    	UpdatePagerViewData(totalPages, totalRows, currentPage, pageSize);
    	
    	List<Customer> customers = query.ToList();
    	return View(customers);
    }
    
    
    private IQueryable<Customer> AddQuerySorting(IQueryable<Customer> query, string sortField, string sortDirection)
    {
    	//Used approach from http://www.singingeels.com/Articles/Self_Sorting_GridView_with_LINQ_Expression_Trees.aspx
    	//instead of a long switch statement 
    	var param = Expression.Parameter(typeof(Customer), "customer");
    	var sortExpression = Expression.Lambda<Func<Customer, object>>
    							(Expression.Convert(Expression.Property(param, sortField), typeof(object)), param);
    
    	if (sortDirection == "Asc")
    		query = query.OrderBy(sortExpression);
    	else
    		query = query.OrderByDescending(sortExpression);
    
    	return query;
    }
    
    
    private void UpdateSorterViewData(string sortField, string sortDirection)
    {
    	ViewData["sortField"] = sortField;
    	ViewData["sortDirection"] = sortDirection;
    }
    

    4. Changed UI to only display asc/desc image next to column being sorted. Also changed column heading labels to links. Used the following CSS to display ASC or DESC image next to link that was sorted.

    #grid #data .asc{
    	background: transparent url('../Content/Images/asc.png') center right no-repeat ;
    }
    
    #grid #data .desc{
    	background: transparent url('../Content/Images/desc.png') center right no-repeat;
    }
    

    5. Made all columns sortable. Moved some of the sorting display logic to controller to prevent too much duplication.

    Html was simplified to look like this:

    <th>
    	<a href="#" class="<%= CustomerController.GetGridThClass(ViewData, "FirstName") %>" 
    				onclick="<%= CustomerController.GetGridThOnClick(ViewData, "FirstName")%>">
    		First Name</a>
    </th>
    

    The new methods in CustomerController are:

    public static string GetGridThClass(ViewDataDictionary<IEnumerable<Customer>> viewData, string sortField)
    {
    	if ((string)viewData["SortField"] != sortField)
    		return "";
    
    	if ((string)viewData["SortDirection"] == "Asc")
    		return "asc";
    	
    	return "desc";
    }
    
    
    public static string GetGridThOnClick(ViewDataDictionary<IEnumerable<Customer>> viewData, string sortField)
    {
    	if ((string)viewData["SortField"] == sortField && (string)viewData["SortDirection"] == "Asc")
    		return "sort('" + sortField + "', 'Desc');";
    
    	return "sort('" + sortField + "', 'Asc');";
    }
    

    Observations

    • Discovered a nice way to post code in WordPress using ‘sourcecode’ tag here: http://support.wordpress.com/code/
    • ViewData is starting to remind me of a ViewState. With all the hidden variables it is basically the same thing. Of course without being bloated and encoded and not usable from JS.

    Coming up…

    At this point we have a grid with server side paging and server side sorting.

    For next part I will create a Grid class/data structure with all the Pager and Sorter properties and pass it as a View model instead of using the non-strong typed ViewData[…].
    I will also add keyword search with auto-complete.

    Create a free website or blog at WordPress.com.