MVC - JQuery - Drag and Drop - Sorting
Below is the code that provides features to drag and drop using jquery sorting features.
Controller Code:
namespace Demo.Web.Controllers
{
public class UserController : Controller
{
public ActionResult Index()
{
return View();
}
public ActionResult GetUsersData()
{
var datalist = BLUsers.GetUserList();
return Json(new { data = datalist.DataList.ToList() }, JsonRequestBehavior.AllowGet);
}
[HttpPost]
public virtual void GetUsersPostData(List<VMUser> savedItems)
{
foreach (var item in savedItems)
{
// TODO: as per your requirement
}
}
}
}
View page code:
@{
ViewBag.Title = "index";
}
<h2>Drag and Drop</h2>
<script src="http://ajax.aspnetcdn.com/ajax/jquery/jquery-1.10.0.min.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.10.3/jquery-ui.min.js" type="text/javascript"></script>
<link href="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.10.3/themes/blitzer/jquery-ui.css" rel="stylesheet" type="text/css" />
<style>
#sortable1, #sortable2 {
border: 1px solid #eee;
width: 142px;
min-height: 120px;
list-style-type: none;
margin: 0;
padding: 5px 0 0 0;
float: left;
margin-right: 10px;
background-color: gray;
}
#sortable1 li, #sortable2 li {
margin: 0 5px 5px 5px;
padding: 5px;
font-size: 1.2em;
width: 120px;
cursor: move;
}
</style>
<script>
$(function () {
$("ul.droptrue").sortable({
connectWith: "ul"
});
$("ul.dropfalse").sortable({
connectWith: "ul"
});
loadUsers();
///Function to load products using call to WEB API
function loadUsers() {
var items = "";
$.ajax({
url: "/demo.web/User/GetUsersData",
type: "GET"
}).done(function (resp) {
$.each(resp.data, function (idx, val) {
items += "<li class='ui-state-default ItemId' id='" + val.UserId + "'>" + val.Username + "</li>";
});
$("#sortable1").html(items);
}).error(function (err) {
alert("Error! " + err.status);
});
}
$("#btnSubmit").click(
function () {
var childCheckBoxes = $("#sortable2 li");
var userViewPreferenceDetails = new Array();
var values = "";
for (i = 0; i < childCheckBoxes.length; i++) {
var userPreferenceItem = new Object();
userPreferenceItem.UserId = childCheckBoxes[i].id;
userViewPreferenceDetails.push(userPreferenceItem);
}
$.ajax({
type: 'POST',
url: '/demo.web/User/GetUsersPostData',
data: JSON.stringify(userViewPreferenceDetails),
dataType: 'json',
contentType: 'application/json; charset=utf-8',
success: function (data) {
alert(data);
},
error: function (jqXHR, status, err) {
alert(err);
},
complete: function (jqXHR, status) {
alert("Local completion callback.");
}
});
});
});
</script>
<ul id="sortable1" class="droptrue"></ul>
<ul id="sortable2" class="dropfalse"></ul>
<div style="clear:both; padding-top:30px">
<input type="button" id="btnSubmit" value="Submit Data" />
</div>
Output:
Enjoy !!!
:)