JQueryが提供するoffset
or関数を使用して、ボタンのメソッドを介して要素の座標をASP.NETコードビハインドに渡す単純なASP.NETサイトを作成しようとしています。position
<div>
OnClick
この例を検索して見つけましたが、クリックしても座標が返されないため、期待どおりに機能しないようです。
<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);
}
});