Introduction
This article shows how to create a sortable item list. Under this you can change the position of the items in the list, drag items and replace other list items.
The following is the procedure for creating the application.
Step 1
First create a Web API application.
- Start Visual Studio 2012.
- From the start window select "New Project".
- From the new project window select "Installed" -> "Visual C#" -> "Web".
- Select "ASP.NET MVC4 Web Application" and click the "OK" button.
- From the "MVC4 Project" window select "Web API".
- Click the "OK" button.
Step 2
Now we write some code in the "_Layout.cshtml" file. This file exists:
- In the "Solution Explorer".
- Expand the "Views" folder.
- Select "Shared" -> "_Layout.cshtml".
Add the following code:
- <!DOCTYPE html>
- <html>
- <head>
- <title>@ViewBag.Title</title>
- <link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />
- <script src="http://code.jquery.com/jquery-1.8.2.js"></script>
- <script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
- </head>
- <body>
- @RenderBody()
- </body>
- </html>
Step 3
Now use the "index.cshtml" file. This file exists:
- In the "Solution Explorer".
- Expand "View" folder.
- Select "Home" -> "index.cshtml".
Add the following code:
- @{
- ViewBag.Title = "This code for creating sortable list in Web API";
- }
- <h3>Sortable values</h3>
- <style type="text/css">
- #Value { list-style-type:square; margin:auto; padding: 0; width: 40%; }
- #Value li { margin: 0 3px 3px 3px; padding: 0.4em; padding-left: 1.5em; font-size: 1.0em; height: 15px; }
- #Value li span { position:absolute; margin-left: -1.3em; }
- </style>
- <script type="text/javascript">
- $(function () {
- $("#Value").sortable();
- $("#Value").disableSelection();
- });
- </script>
- <ul id="Value">
- <li class="ui-state-default"><span class="ui-icon ui-icon-arrowthick-2-n-s"></span>Value 1</li>
- <li class="ui-state-default"><span class="ui-icon ui-icon-arrowthick-2-n-s"></span>Value 2</li>
- <li class="ui-state-default"><span class="ui-icon ui-icon-arrowthick-2-n-s"></span>Value 3</li>
- <li class="ui-state-default"><span class="ui-icon ui-icon-arrowthick-2-n-s"></span>Value 4</li>
- <li class="ui-state-default"><span class="ui-icon ui-icon-arrowthick-2-n-s"></span>Value 5</li>
- <li class="ui-state-default"><span class="ui-icon ui-icon-arrowthick-2-n-s"></span>Value 6</li>
- <li class="ui-state-default"><span class="ui-icon ui-icon-arrowthick-2-n-s"></span>Value 7</li>
- </ul>
Step 4
Now execute the application by pressing "F5". The output looks like this:
Now move the item from one location to another.
After moving the item the list looks like this:
After refreshing the page, the changes that you made in the list are lost.