Introduction
This tip contains a solution for creating a priority grid. There are scenarios when you use a grid in your application for a specific purpose. For example, you need a grid to increase or decrease the priority of the individual selected row. In that case, you don’t need to deploy a feature heavy grid. The priority grid, as the name indicates, should be sufficient for such limited purpose use. The application uses MVC / JSON with LINQ to handle the data access in the grid.
Background
The ASP.NET MVC Framework's Model View Controller pattern is increasingly growing in popularity for enabling users to build flexible, easily tested Web applications. A MVC application is also easy to maintain compared to web form application. Such an application would keep the main application code separate from persistence logic as well as from the front end view.
Using the Code
In our sample application, we use a repository (class) that performs the Linq query to retrieve the data from the input XML (note that we are using an XML file to populate the data in the grid). The MVC controller instantiates and calls the repository method to get the data. That way, any other controller that needs the same data can use the same repository without duplicating the code. We use separate classes within the model to pass data between controller and repository. To run the application, open the Visual Studio 2012 project and start. The application uses MVC ViewData; the ViewData (named ‘data’) is populated by LINQ call to the input XML and the returned ‘data’ is passed on to the front end jQuery html()
method.
The increment priority method uses the following code:
var item1 = data[ind];
var item2= data[ind-1];
data[ind-1]=item1;
data[ind]=item2;
The grid is refreshed after the current row is swapped with the previous as shown above. The Save
method uses the code below:
var myiD = Array();
$.each(data, function (index, value) {
myiD.push(value['id']);
});
It then makes an AJAX request with jQuery and JSON to the MVC controller to update the priority (of the rows) in the XML.
Points of Interest
jQuery with LINQ has recently received a huge surge of interest of the ASP.NET MVC. I wanted to create an example where I would invoke an AJAX call to dynamically populate a grid with the additional functionality of increasing (or decreasing) the priority of the selected row. I've been impressed not only with how few lines of JavaScript it takes me to get things done, but also how (relatively) easy it was to learn. This application works for small or short-lived applications, but can also be extended for large applications.
History
- 19th March, 2013: Initial version