Simon Miller Team : Web Development Tags : Web Development

MVC and its tight integration with JQuery

Simon Miller Team : Web Development Tags : Web Development

We develop a lot in Microsoft MVC 3 and thought I would share one of the “wow, that’s cool” parts of it.

The tight integration with JQuery is one such “how did I ever do this before?” kind of deals. I needed to construct a basic, sortable list of items and I wanted to use JQuery sortable() to for the UI. That part was easy enough; but how do we send this changed order server-side? Painlessly, that’s how.

Here is part of the view that loops through Images in my model. The model contains Name (string), ID (int) and SortOrder (int). The SortOrder loads in steps of 1 from the model on load (0, 1, 2, etc.) 

The JQuery component is extremely simple. The sortable() method has an event called ‘stop’ that fires when you have re-ordered an item in the list. The first part of the function is to re-assign the SortOrder values to the re-ordered list. 

The second part of the function is the magic: using JQuery Ajax, and by serialising the form, the model can be sent directly to your controller and then on to the database.

Simple! The model is available to the controller and can be passed onto a private database function to commit the SortOrder values back to the database.