![](/img/trans.png)
[英]Pass jQuery Variable into ASP.NET Code Behind Using HiddenField
[英]JQuery - Pass coordinates of element to ASP.NET code behind?
我正在嘗試創建一個簡單的ASP.NET網站,該網站將使用JQuery提供的offset
或position
函數通過按鈕的OnClick
方法將<div>
元素的坐標傳遞給ASP.NET代碼。
我已經搜索並找到了此示例,但按一下似乎沒有按預期工作,單擊后沒有返回坐標。
如何獲取給定<div>
元素的坐標,並將其傳遞給ASP.NET按鈕的OnClick
方法?
第1部分
要獲取元素的位置,可以使用offset()或position()
小提琴: http : //jsfiddle.net/XFfLP/
function test() {
var p = $("#testID");
var position = p.offset();//p.position()
$("#Field1").val(position.top);
$("#Field2").val(position.left);
}
第2部分
要將數據從頁面傳遞到背后的服務器代碼,可以使用Web-Methods
文章: http : //blog.nitinsawant.com/2011/09/draft-sending-client-side-variables-to.html
1. Web方法示例代碼:
[System.Web.Services.WebMethod]
public static string AcceptData(object jsonData)
{
Customer newCust =(Customer)JsonConvert.DeserializeObject(jsonData.ToString(),typeof(Customer));
return "Server response: Hello "+newCust.FirstName;
}
2. JS示例代碼:
var newCustomer = {
"FirstName": $("#txtFirstName").val(),
"LastName": $("#txtLastName").val(),
"Telephone": $("#txtTelephone").val()
}
var jsonData = "{'jsonData':'" + JSON.stringify(newCustomer) + "'}";//create string representation of the js object
//post data to server
$.ajax({
type: "POST",
url: 'Test.aspx/AcceptData',
data: jsonData,
contentType: "application/json; charset=utf-8",
dataType: ($.browser.msie) ? "text" : "json",
success: function(msg) {
//call successfull
var obj = msg.parseJSON();
alert(obj.d); //d is data returned from web services
//The result is wrapped inside .d object as its prevents direct execution of string as a script
},
error: function(xhr, status, error) {
//error occurred
alert(xhr.responseText);
}
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.