Retaining drag position does not work: jQuery draggable: position() - c#

I have the following code which will store coordinate positions of the div whenever it is moved. The positions are stored into database so that when user returns, it remains there. The following code works somewhat similar to that. But the positions are not accurately maintained when I do two – three movements.
Note: I think the problem is following lines of code
//var absolutePositionLeft = (ui.originalPosition.left) + (ui.offset.left);
//var absolutePositionTop = (ui.originalPosition.top) + (ui.offset.top);
var stopPositions = $(this).position();
var absolutePositionLeft = stopPositions.left;
var absolutePositionTop = stopPositions.top;
Note: I am getting the error "Microsoft JScript runtime error: 'absolutePosition.left' is null or not an object" when I use var absolutePositionLeft = ui.absolutePosition.left;
Can you please suggest how to overcome this?
The code:
<head runat="server">
<title></title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/jquery-ui.min.js"></script>
<script type="text/javascript">
$(function () {
$("#<%=dImage.ClientID%>").draggable(
{
drag: function (event, ui) {
//when dragging
$("#<%=dImage.ClientID%>").css("opacity", "0.3");
},
stop: function (event, ui) {
//when stopped
//showAlert();
debugger;
//var absolutePositionLeft = (ui.originalPosition.left) + (ui.offset.left);
//var absolutePositionTop = (ui.originalPosition.top) + (ui.offset.top);
var stopPositions = $(this).position();
var absolutePositionLeft = stopPositions.left;
var absolutePositionTop = stopPositions.top;
var elementName = ui.helper.attr('id');
saveCoords(absolutePositionLeft, absolutePositionTop, elementName);
$("#<%=dImage.ClientID%>").css("opacity", "1.0");
},
cursor: "move"
});
});
function showAlert()
{
alert("hai");
}
function saveCoords(x, y, el, id)
{
$.ajax({
type: "POST",
url: "GridViewHighlightTEST.aspx/SaveCoords",
data: "{x: '" + x + "', y: '" + y + "', element: '" + el + "', userid: '1'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response)
{
if (response.d != '1')
{
alert('Not Saved!');
}
},
error: function (response)
{
alert(response.responseText);
}
});
}
</script>
And the C# Code is
protected void Page_Load(object sender, EventArgs e)
{
DataTable dt = GetSavedCoords(1);
foreach (DataRow row in dt.Rows)
{
string elementName = row["element"].ToString();
System.Web.UI.HtmlControls.HtmlControl theControlElement = (HtmlControl)this.FindControl(elementName);
if (theControlElement != null)
{
theControlElement.Style.Add("left", row["xPos"].ToString() + "px");
theControlElement.Style.Add("top", row["yPos"].ToString() + "px");
}
}
}

I believe your problem is that
var stopPositions = $(this).position();
should be
var stopPositions = $(event.target).position();
In any case, it's extremely useful to use a JavaScript debugger, it will keep you sane. If you are using Chrome or IE use F12 to get to developer tools. If you're using Firefox get Firebug.
Using one of these tools can help you quickly verify what this actually is which, depending on the frameworks your using, can quickly get confusing. A debugger can also help you verify your DOM and code flow.

Related

Web method 404 not found after publishing to production server

The following code is working perfecting after publishing to my localhost. So I copied the files from my localhost and put them on the server. Now it's saying it cannot find the web method. The project is an MVC project and what's not working is an separate aspx page added to the project directory. So, I don't know if this has something to do with IIS. Any ideas would be greatly appreciated.
[WebMethod]
public static string LoadPatients(string phone, string user)
{
//SOME STUFF HERE THAT WAS EXCLUDED//
var sb = new StringBuilder();
for (var x = 0; x < Callerdt.Rows.Count; x++)
{
var addr = Callerdt.Rows[x]["Street"].ToString() + " " + Callerdt.Rows[x]["city"].ToString() + ", " + Callerdt.Rows[x]["State"].ToString() + " " + Callerdt.Rows[x]["ZipCode"].ToString();
sb.AppendFormat("<div class='tabs'><table>" +
"<tr><td class='title'><label>Name:</label></td><td>{0}</td></tr>" +
"<tr><td><label>DOB:</label></td><td>{1}</td></tr>" +
"<tr><td><label>Address:</label></td><td>{2}</td></tr>" +
"<tr><td><label>SSN:</label></td><td>{3}</td></tr>" +
"<tr><td><label>Z Number:</label></td><td>{4}</td></tr>" +
"</table></div><br/>", Callerdt.Rows[x]["Name"].ToString(), Callerdt.Rows[x]["DOB"].ToString(), addr, Callerdt.Rows[x]["SSN"].ToString(), Callerdt.Rows[x]["ZNUM"].ToString());
}
ret = sb.ToString();
return ret;
}
<script type="text/javascript">
$(document).ready(function () {
var p = document.getElementById('pn').value, u = document.getElementById('user').value, er = document.getElementById('error').value;
if (!(er == "true")) {
$("#loading").show();
$.ajax({
type: "POST",
url: 'CallerPopup.aspx/LoadPatients',
data: JSON.stringify({ phone: p, user: u }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
$('#tabs').append(data.d);
},
complete: function () {
$("#loading").hide();
}
});
}
});
</script>
In my case, adding IgnoreRoute to RegisterRoutes() got me going. Now the aspx.cs "static" hosted [webmethod] loads ... url: 'LearnKO.aspx/FetchStudents',
aJax was throwing a 404 - Not Found on any page.aspx/webmethod call.
ie. the fix:
routes.IgnoreRoute("{resource}.aspx/{*pathInfo}");
I was setting up http://www.c-sharpcorner.com/UploadFile/1492b1/learning-knockout-part-1-introduction-to-knockout-js-and-cr/ in an MVC project instead of the recommended empty ASP.NET... my bad.

Retrieve JSON Array from jQuery Ajax call in asp.net webpages

I am trying to send some data through an ajax call of jQuery. My question is : how do I get hold of this JSON array in my Insert.cshtml file? I have tried Request["rows"], Request[0][rows], etc. but without any success.
Here, the data I am trying to send is this (multiple rows of form data):
[
{
"sl": "1",
"tname": "Gardening",
"ttype": "4",
"tduration": "12"
},
{
"sl": "2",
"tname": "Nursing",
"ttype": "4",
"tduration": "45"
}
]
jQuery Code:
$.ajax({
type: "POST",
url: "/Insert",
data: rows,
contentType: "application/json",
success: function (data, status) {
alert(status);
},
error: function (xhr, textStatus, error) {
var errorMessage = error || xhr.statusText;
alert(errorMessage);
}
});
Update: A partial demo in jsfiddle - http://jsfiddle.net/rafi867/gprQs/8/
I have tried to simulate your problem creating in App_Code a Sample.cs class:
public class Sample
{
public string sl { get; set; }
public string tname { get; set; }
public string ttype { get; set; }
public string tduration { get; set; }
}
Now your Insert.cshtml file should look like this:
#{
var sample = new Sample[]{
new Sample{ sl = "1", tname = "Gardening", ttype = "4", tduration = "12" },
new Sample{ sl = "2", tname = "Nursing", ttype = "4", tduration = "45" }
};
Json.Write(sample, Response.Output);
}
and the file (ReadSample.cshtml?) that holds your Sample objects should be:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title></title>
<script src="~/Scripts/jquery-1.4.2.min.js" type="text/javascript"></script>
<script type="text/javascript">
$.getJSON('/Insert', function (sample)
{
var custList = "";
$.each(sample, function (index, obj) {
custList += "<li>" + obj.sl + " - " + obj.tname +
" - " + obj.ttype + " - " + obj.tduration + "</li>";
})
$("#list").html("<ul>" + custList + "</ul>")
})
</script>
</head>
<body>
<div id="list"></div>
</body>
</html>
In my example I have readed the objects array with
$.getJSON('/Insert', function (sample)
and created an unordered list to display its content
$.each(sample, function (index, obj) {
custList += "<li>" + obj.sl + " - " + obj.tname +
" - " + obj.ttype + " - " + obj.tduration + "</li>";
})
$("#list").html("<ul>" + custList + "</ul>")
I hope this could help.
I have put a sample code for show how to display array items on web page by using jquery and css. By using this try to understand the concept and then apply it to your scenario.
HTML
<div class="dialog" id="unpaid-dialog" data-width="550" data-title="Checkout">
<ul>
<li id="serviceAndRetailDetails" style="text-align: left;"></li>
</ul>
</div>
Jquery
<script type="text/javascript">
var toBePaidItems = new Array();//create a array
var make = "";
$.ajax({
type: "GET",
url: "/Portal/GetServiceAndRetailSalesDetails",
dataType: 'json',
contentType: "application/json; charset=UTF-8",
data: { invoiceOrSaleId: invoiceOrSaleId, providerKey: providerKey },
success: function (response) {
make = "<table id='tblPayment'>";
toBePaidItems = [];
$.each(response, function (index, sr) {
make += "<tr id=" + sr.AllocationOrInvoiceOrSaleId + " class=" + sr.Class + ">" + "<td style='padding-right:100px'>" + sr.Name + "</td><td class='colTotal' style='padding-right:45px'>" + '$ ' + sr.Price.toFixed(2) + "</td><td></tr>";
//insert into array
toBePaidItems.push(sr.AllocationOrInvoiceOrSaleId);
});
make += "</table>";
$("#serviceAndRetailDetails").html(make);
}
});
</script>
Controller Action Method
[HttpGet]
public JsonResult GetServiceAndRetailSalesDetails(Guid invoiceOrSaleId, string providerKey)
{
var items = new List<CheckOutServiceAndRetailItem>();
var serviceDetails = Repository.GetAllPayableItems(invoiceOrSaleId).ToList();
foreach (var s in serviceDetails)
{
var item = new CheckOutServiceAndRetailItem
{
AllocationOrInvoiceOrSaleId = s.Allocation.AllocationId,
Name = s.Allocation.Service.Name,
Price = s.LatestTotal,
Class = s.Allocation.Service.IsAnExtra,
};
items.Add(item);
}
return Json(items, JsonRequestBehavior.AllowGet);
}
Array Out Put
How to manipulate Arrays Here
Hope This will help to you.
The data parameter is meant to map name-value pairs to query string parameters as you can tell by the docs:
data
Data to be sent to the server. It is converted to a query string, if
not already a string. It's appended to the url for GET-requests. See
processData option to prevent this automatic processing. Object must
be Key/Value pairs. If value is an Array, jQuery serializes multiple
values with same key based on the value of the traditional setting
(described below).
If you then go on to read the docs for the .param() method, this should help you understand what's going on with your request and how jQuery sends your object to the server.
You may just have to name your objects/arrays in your data object so you can refer to them in the Request.Forms object.

jQuery AutoComplete multiple Output

I am using jQuery AutoComplete to fetch results from a DataBase based on the value inputted. The user will then click a search button to tell the page to search for that specific entries details.
I want to get 2 values, the Name and Title. I only want to display the Name to the user, while the page uses the Title as a search criteria.
eg: When a person types in Vehicle, the result will display Vehicle1, Vehicle2 in a list.
When the user clicks on Vehicle1, a hidden box will be issues with the Title, which would be Bike, and such as with Vehicle2, which will issue the hidden box with Car.
I can get the Name to show in the text box properly, but I cannot for the life of me (And after 2 days of searching) bind the Title to a hidden box.
JavaScript:
<script type="text/javascript" src="http://code.jquery.com/jquery-1.8.2.js"></script>
<script type="text/javascript" src="http://code.jquery.com/ui/1.9.0/jquery-ui.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$(".tb").autocomplete({
source: function (request, response) {
$.ajax({
url: "AutoComplete.asmx/FetchEmailList",
data: "{ 'prefix': '" + request.term + "' }",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
dataFilter: function (data) { return data; },
success: function (data) {
response($.map(data.d, function (item) {
return {
//value: item.Title,
label: item.Name
};
}));
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
}
});
},
minLength: 2
});
});
</script>
ASPX Code:
<div class="ui-widget" >
<asp:TextBox ID="tbAuto" class="tb" runat="server">
</asp:TextBox>
<asp:TextBox runat="server" ID="tbHidden" class="tb"></asp:TextBox>
</div>
CodeBehind:
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ScriptService]
public class AutoComplete : System.Web.Services.WebService
{
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public List<Employee> FetchEmailList(string prefix)
{
var emp = new Employee();
var fetchEmail = emp.GetEmployeeList(prefix)
.Where(m => m.Name.ToLower().StartsWith(prefix.ToLower()));
return fetchEmail.ToList();
}
}
CompletionClass: (Excuse the naming)
public class Employee
{
public string Title { get; set; }
public string Name { get; set; }
public string value { get; set; }
public List<Employee> GetEmployeeList(string prefixText)
{
List<Employee> cmpList = new List<Employee>();
SqlConnection db = DataConn.SqlConnection();
db.Open();
SqlTransaction transaction = db.BeginTransaction();
//var array = new ArrayList();
try
{
SqlCommand command = new SqlCommand("Select [something] FROM vwGetDetails WHERE [something_else] LIKE N'%" + prefixText + "%' ORDER BY [thatOther_thing] ASC", db, transaction);
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
cmpList.Add(new Employee() { Name = reader["Value1"].ToString(), Title = "Value1_Cat", value = "Value1_Cat"});
}
}
command = new SqlCommand("Select [something] FROM [somewhere] WHERE [thingy] LIKE N'%" + prefixText + "%' ORDER BY [previousThingy] ASC", db, transaction);
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
cmpList.Add(new Employee() { Name = reader["Value2"].ToString(), Title = "Value2_Cat", value = "Value2_Cat"});
}
}
transaction.Commit();
}
catch (SqlException)
{
transaction.Rollback();
cmpList.Add(new Employee() { Name = "Problem Getting Results.", value = "Error"});
//array.Add("Problem Getting Results.");
}
if (cmpList.Count == 0)
cmpList.Add(new Employee() { Name = "Nothing to Display.", value = "Info"});
//array.Add("Nothing to Display.");
//return array;
return cmpList;
}
}
Those modifications to your JavaScript should do the trick:
<script type="text/javascript" src="http://code.jquery.com/jquery-1.8.2.js"></script>
<script type="text/javascript" src="http://code.jquery.com/ui/1.9.0/jquery-ui.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$('input[name$="tbAuto"]').autocomplete({
source: function (request, response) {
$.ajax({
url: "AutoComplete.asmx/FetchEmailList",
data: "{ 'prefix': '" + request.term + "' }",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
dataFilter: function (data) { return data; },
success: function (data) {
response(data.d);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
}
});
},
minLength: 2,
focus: function(event, ui) {
$('input[name$="tbAuto"]').val(ui.item.Name);
return false;
},
select: function(event, ui) {
$('input[name$="tbAuto"]').val(ui.item.Name);
$('input[name$="tbHidden"]').val(ui.item.Title);
return false;
}
}).data('autocomplete')._renderItem = function(ul, item) {
return $('<li>').data('item.autocomplete', item).append('<a>' + item.Name + '</a>').appendTo(ul);
};
});
</script>
The assumption here is that the selectors returns exactly the element which we are working on, if not they need to be adjusted.
Cool. I've been googling for this solution for days... excellent clean code!
Just a small remark: using jqueryUI 1.10, this
throws javascript exception.
.data('autocomplete')._renderItem = function(ul, item) {...
I've used
.data('ui-autocomplete')._renderItem = function(ul, item) {...
and everything works great.

Asp.Net + JQuery - Set CSS in function.Ready

I need to set CSS values in the ready function below.
$(document).ready(function ()
{
$("<div id='" + 1 + "' class='box'></div>").css("left", 105).css("top", 54).appendTo("#center").draggable();
$("<input type='text'></input>").appendTo("#" + 1);
}
It works fine, then it create a textbox within a draggable div and place them at top:54 and left 105. Now I need to get X,Y from server query, and I've tried this:
$(document).ready(function ()
{
$.ajax({
type: "POST",
url: "Default.aspx/Get",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg)
{
var singleControls = msg.d.split('.');
$.each(singleControls, function (key, value)
{
var singleParameters = value.split(',');
if (singleParameters[0] != "")
{
var ids = singleParameters[0];
var type = singleParameters[1];
var cordX = singleParameters[2];
var cordY = singleParameters[3];
var container = $("#center").position();
var x_Coord = cordX - container.left;
var y_Coord = cordY - container.top;
$("<div id='" + ids + "' class='box'></div>").css("left", cordX).css("top", cordY).appendTo("#center").draggable();
$("<input type='text'></input>").appendTo("#" + ids);
}
});
}
});
Where Get() returns X,Y, with this it creates the div, but it places it at 0,0.
Can someone please explain why this isn't working?
sample: https://skydrive.live.com/redir.aspx?cid=d7fc3da7fdbc700d&resid=D7FC3DA7FDBC700D!302&parid=D7FC3DA7FDBC700D!301
if you are hard coding the left and top styles, then why not add them to the .box style in your style sheet like so
.box{
position:absolute;
left:105px;
top:54px;
}
otherwise the css function should look like the following:
.css({
position:'absolute',
left:'105px',
top:'54px',
});​
here is a jsfiddle.net example

Create a query suggestion page based on keywords

I have an asp.net page and am writing some words in a question textbox named txtTitle. After moving to another txtbox named txtbox2, I want to open a question-suggestion page based on the keyword typed in txtbox1 in the space before txtbox2. I've tried this but it is not working. Can anyone help?
<script type="text/javascript">
$(function() {
$("#txtTitle").blur(function() { QuestionSuggestions(); });
});
function QuestionSuggestions() {
var s = $("#txtTitle").val();
if (s.length > 2) {
document.title = s + " - ABC";
$("#questionsuggestions").load("QuestionList.aspx?title=" + escape(s));
}
}
</script>
Create a WebService WebMethod in ASP.Net/C# that loads the suggestions. Your code in the WebMethod will load the datatable with the suggestions. In your WebMethod, return the DataTable as a hashtable, and it will automatically be converted to a JSON object.
public Suggestions<Hashtable> GetSuggestion()
{
DataTable dt = new DataTable();
List<Hashtable> ht = new List<Hashtable>();
string q = Context.Request.QueryString["Q"];
dt = [code to load datatable]
ht = MethodToConvertToHashTable(dt);
dt.Dispose();
return ht;
}
In your txtTitle.blur function, call question suggestions, which does a jQuery AJAX call to the webmethod (I left out the obvious).
function QuestionSuggestions() {
var s = $("#txtTitle").val();
var myJSON = $.ajax({
url: '/directory/svc/yourwebservicepage.asmx/GetSuggestion?Q=' + s,
type: 'POST',
contentType: 'application/json',
success: function (msg) {
var d = msg.d; //THIS IS YOUR JSON OBJECT
}
}
}

Categories

Resources