|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
Announcements
Chapters
Services
Feature Zones
|
IntroductionEver been on a Web site that shows off the drag and drop operation? Maybe it allows you to drag and drop the product into a shopping cart. Most of us have been there and were really impressed with the feature. In this article, we will focus on how to create a similar drag and drop functionality to add users to a room. Why JQuery?Why indeed? There are several drag and drop libraries available for free. Take Microsoft ASP.NET Ajax, for example. Unfortunately, the Microsoft Ajax Library is not developer friendly, meaning it is darn complicated to use. So, if you are looking for some head-banging, be sure to dive into Microsoft Ajax. However, if you are interested in a simple and powerful approach, then Some of you might be thinking, "Why not simply write plain old vanilla JavaScript?" Well, off course you can, but that is also a very complicated and time-consuming approach. If you are interested in using only JavaScript, then check out the article, "Browser Compatible Drag and Drop Shopping Cart". Downloading JQuery and UI APIBefore we implement anything, we need to download the ScenarioThe scenario is a little different from the shopping cart basket. In this application, we are going to drag and drop the users to a room. Once a user is inserted into the room, an entry is written to the database. We can also delete the user from the room. In that case, the entry is deleted from the database. Check out the GIF using the link, "Drag and Drop With Persistence Using JQuery". DatabaseThere is one table, The table script is included with the download. Populating the Students ListThere are multiple ways of populating the student Student DataList Control ASPX CodeThe ASPX code for the <asp:DataList ID="dlRooms" EnableViewState="false" runat="server" RepeatColumns="3"
RepeatDirection="Horizontal">
<ItemTemplate>
<div id="div1" class="block">
<div style="text-align:center; font-size:18px; border:solid 1px">
<%# Container.ItemIndex + 1 %></div><li id="username" runat="server">
<%# Eval("UserName") %></li><li id="roomId" runat="server" style="visibility:hidden">
<%# Eval("RoomID") %></li><li>
<%# Eval("Subject") %></li><li>
<%# Eval("Description") %></li></div></ItemTemplate></asp:DataList>
When the The numbers indicate the order in which students requested the room. This means that the student with number <%# Container.ItemIndex + 1 %>
You will also notice that the CSS StylesThere are several CSS styles used in this application. Let’s take a look at a few of them. .block {
border: 2px solid #0090DF;
background-color: #68BFEF;
width: 200px;
height: 200px;
margin: 10px;
overflow:auto;
padding:1em 1em 1em 1em;
z-index:9999;
cursor:move;
}
The .roomItem {
border: 2px solid #0090DF;
background-color: yellow;
}
The .drop {
background-color: #e9b96e;
border: 3px double #c17d11;
width: 300px;
height: 300px;
margin: 10px;
overflow:auto;
position:absolute;
top: 5px;
right: 10%;
padding: 1em 0 0 0;
}
The Making Items Draggable and Droppable using JQueryLet me first post the complete code and then I will explain the code in segments. $(document).ready(function(){
$(".block").draggable({helper:'clone'});
$(".drop").droppable({
accept: ".block",
activeClass: 'droppable-active',
hoverClass: 'droppable-hover',
drop: function(ev, ui) {
$(ui.draggable).addClass("roomItem");
var lid = ($(ui.draggable).children("li:first"));
// gets the username
var username = ($(ui.draggable).children("li:first").text()).replace(/[\n\r\t]/g,'');
var roomId = $(ui.draggable).children("li:eq(1)").text();
var removeLink = document.createElement("a");
removeLink.innerHTML = "remove";
removeLink.href = "#";
removeLink.onclick = function()
{
$("#drop1").children().remove("#"+lid[0].id);
$(this).remove();
// removes the class
$(ui.draggable).removeClass("roomItem");
// adds the new class
$(ui.draggable).addClass("block");
// remove the user session from the database
VirtualTutoringRoomWebApps.VirtualRoomService.removeUserFromRoom(
username,Number(roomId));
}
$(this).append($(ui.draggable).clone().children("li:first").addClass("roomItem"));
$(this).append(removeLink);
// add user to the room
VirtualTutoringRoomWebApps.VirtualRoomService.addUserToRoom(username,Number(roomId));
}
});
});
Seems complicated! Don't worry; it is not that hard to understand. Let's start with the To make the element draggable, all you need to do is use the draggable function provided in the $(".block").draggable({helper:'clone'});
The same technique is used for creating the drop zone. When the item is dropped inside the drop zone, a class called // gets the username
var username = ($(ui.draggable).children("li:first").text()).replace(/[\n\r\t]/g,'');
var roomId = $(ui.draggable).children("li:eq(1)").text();
A new hyperlink element is created that is used to remove the items from the drop zone. Basically, the var removeLink = document.createElement("a");
removeLink.innerHTML = "remove";
removeLink.href = "#";
removeLink.onclick = function()
{
$("#drop1").children().remove("#"+lid[0].id);
$(this).remove();
// removes the class
$(ui.draggable).removeClass("roomItem");
// adds the new class
$(ui.draggable).addClass("block");
// remove the user session from the database
VirtualTutoringRoomWebApps.VirtualRoomService.removeUserFromRoom(
username,Number(roomId));
}
When the item is removed from the drop zone, it is returned back to its original class, which is $(this).append($(ui.draggable).clone().children("li:first").addClass("roomItem"));
$(this).append(removeLink);
// add user to the room
VirtualTutoringRoomWebApps.VirtualRoomService.addUserToRoom(username,Number(roomId));
Check out the screenshot below, which shows the item added to the drop zone. Finally, the Ajax MethodsI have used Microsoft ASP.NET Ajax to create asynchronous calls to the Web service methods. Let's take a look at these methods: [WebMethod]
public bool removeUserFromRoom(string username, int roomId)
{
MethodInvoker.Invoke<SQLDataAccess>("RemoveUserFromRoom", new object[]
{
username.Trim(), roomId
});
return false;
}
[WebMethod]
public bool addUserToRoom(string username, int roomId)
{
try
{
MethodInvoker.Invoke<SQLDataAccess>(
typeof(tblRoomSession), "AddAndPersistAll",
new object[]
{
new tblRoomSession()
{
Guid = Guid.NewGuid().ToString(), RoomID = roomId,
StudentUserName = username.Trim(),
TutorUserName = User.Identity.Name, IsSessionStarted = true,
SessionStartDate = DateTime.Now
}
});
}
catch (Exception ex)
{
string exception = ex.Message;
}
return false;
}
Don't pay that much attention to the Additional FeaturesThere are several additional features that need to be implemented for this application. Some of them are listed below:
UpdateWhen this was published, we talked about few additional features that might be useful. Some of them are shown above under the "Additional Features" section. Here is the implementation of both the features. First, let's see how we can update the interface when a new user enters the waiting list. This process should be done asynchronously which means that the screen should not refresh on the server side but on the client side. As it turns out, this can easily be accomplished by using the ASP.NET <triggers>
<asyncpostbacktrigger eventname="Tick" controlid="timer1">
</triggers>
Now, let's see the Timer control which is also contained inside the <timer id="timer1" ontick="timer1_Tick" interval="5000" runat="server" />
The protected void timer1_Tick(object sender, EventArgs e)
{
BindData();
up1.Update(); }
That was simple! The The reason is that when you updated the screen using the protected void timer1_Tick(object sender, EventArgs e)
{
BindData();
up1.Update();
RegisterDragAndDropScript();
}
// this method is fired to register the scripts again
// since the timer will refresh the contents of the
// update panel and hence the HTML controls will lose
// the drag and drop capability
private void RegisterDragAndDropScript()
{
string script = "makeElementsDraggableAndDroppable();";
ScriptManager.RegisterClientScriptBlock(this,this.GetType(),
"DragAndDropScript", script, true);
}
Now, when the ConclusionIn this article, we learned how to create a drag and drop UI using History
|
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||