C# 将值从 javascript 传递到 Codebehind
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19443012/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
pass the values from javascript to Codebehind
提问by user2423434
I am new to ASP.NET
我是 ASP.NET 的新手
I want to implement the website about..
我想实施关于..的网站
- draw(add) some points. (the number of points: depend on user★)
- user move these points within gray box
- upload locations(top, left) of these points into Database.
- 绘制(添加)一些点。(点数:取决于用户★)
- 用户在灰框中移动这些点
- 将这些点的位置(顶部,左侧)上传到数据库中。
I understood how to add draggable points and get coordination of these.
我了解如何添加可拖动点并协调这些点。
And I want to know..
而且我想知道..
how to pass some values to codebehind part without reload pages.
how to pass values and use these without knowing how many value it is.
如何在不重新加载页面的情况下将一些值传递给代码隐藏部分。
如何在不知道有多少值的情况下传递值和使用这些值。
Could you give me some advice or some link about my question?
你能给我一些建议或一些关于我的问题的链接吗?
Thank you in advance.
先感谢您。
here is my code.
这是我的代码。
You can check this out in here (http://jsfiddle.net/crisply/mQYVY/21/)
你可以在这里查看(http://jsfiddle.net/crisply/mQYVY/21/)
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="jQueryDraggable.aspx.cs" Inherits="WebPage.Tests.jQueryDraggable" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title></title>
<script type="text/javascript" src="../Scripts/jquery-1.8.2.js"></script>
<script type="text/javascript" src="../Scripts/jquery-ui-1.8.24.js"></script>
<style type="text/css">
.draggable {
position: absolute;
width: 10px;
height: 10px;
background: green;
cursor: move;
}
.canvas {
width: 500px;
height: 400px;
background: #ccc;
position: relative;
margin: 2em auto;
}
#results {
text-align: center;
}
</style>
<script type='text/javascript'>
//<![CDATA[
$(function () {
var index = 1;
$(".draggable").draggable({
containment: "parent",
});
$('#btn_add').click(function () {
var pointID = "Point" + (index++);
var top = Math.floor(Math.random() * 501);
var left = Math.floor(Math.random() * 401);
drawPoint(pointID, top, left);
});
$('#btn_getCoord').click(function () {
writeCoordination();
});
$('#btn_erase').click(function () {
eraseAllPoint();
writeCoordination();
});
function drawPoint(pointId, top, left) {
var htmlData = $('<div class="draggable" id=' + pointId + '>' + pointId + '</div>');
htmlData.css({ 'left': top + 'px', 'top': left + 'px' });
$('.canvas').append(htmlData);
$(".draggable").draggable({ containment: "parent" });
}
function writeCoordination() {
var output = '-Coordination-';
$('.draggable').each(function () {
output += '<br />' + $(this).attr("id") + ' => x: ' + $(this).position().left + ', y: ' + $(this).position().top;
});
$('#results').html(output);
}
function eraseAllPoint() {
$('.canvas').html('');
}
});
//]]>
</script>
</head>
<body>
<form id="form1" runat="server">
<div class="canvas">
<div class="draggable" id="Point0">Point0</div>
</div>
<div id="results">coordination</div>
<input type='button' id="btn_add" value='Add box' />
<input type='button' id="btn_getCoord" value="Get Coornination" />
<input type='button' id="btn_erase" value='Erase All' />
<asp:Button ID="btn_submit" runat="server" Text="Upload" />
</form>
</body>
</html>
采纳答案by Anthony Horovitz
You need to use AJAX for this.
为此,您需要使用 AJAX。
Here is the simplest possible example that will work but this is only to get you started. I oversimplified this for the demonstration purposes and it's not really high quality.
这是最简单的示例,它可以工作,但这只是为了让您入门。为了演示目的,我过度简化了它,它的质量并不高。
Javascript code
Javascript代码
Much better way to send data is through POST because GET is limited to around 2000 characters.
发送数据的更好方法是通过 POST,因为 GET 限制在 2000 个字符左右。
Also, better way to format your data points would be through JSON. What I've shown below is not the best practice really ;)
此外,格式化数据点的更好方法是通过 JSON。我在下面展示的并不是最佳实践;)
<script type="text/javascript">
var xmlHttpRequest;
function PostData() {
//create XMLHttpRequest object
xmlHttpRequest = (window.XMLHttpRequest) ? new XMLHttpRequest() : new ActiveXObject("Msxml2.XMLHTTP");
//If the browser doesn't support Ajax, exit now
if (xmlHttpRequest == null)
return;
//Prepare your data points so they are in the format X1-Y1-X2-Y2-X3-Y3
pointData = "21-12-51-23-54-125-154-315-245-21"
//Initiate the XMLHttpRequest object
xmlHttpRequest.open("GET", "http://foo.com/Page.aspx?Points=" + pointData, true);
//Send the Ajax request to the server with the GET data
xmlHttpRequest.send(null);
}
</script>
C# code on the server
protected void Page_Load(object sender, EventArgs e)
{
if (Request.QueryString["Points"] != null)
{
string rawData = Request.QueryString["Points"];
string []points = rawData.Split(new string[] { "-" }, StringSplitOptions.None);
//continue parsing these to Ints and more...
}
}
Here are couple tutorials and resources that will help you to polish this up some more
这里有几个教程和资源,可以帮助您进一步完善它
http://www.codeproject.com/Articles/31155/Ajax-Tutorial-for-Beginners-Part-1
http://www.codeproject.com/Articles/31155/Ajax-Tutorial-for-Beginners-Part-1
回答by Saritha.S.R
its not possible to access a js-variable from codebehind without any help of a server-control. You could redirect the page to itself and pass that value as URL-Parameter(window.location.href = window.location.href + "?value=test";). But i assume that this is not what you want because it forces a postback. So the best way is to use a hiddenfield:
如果没有服务器控件的任何帮助,就不可能从代码隐藏访问 js 变量。您可以将页面重定向到自身并将该值作为 URL-Parameter(window.location.href = window.location.href + "?value=test";) 传递。但我认为这不是您想要的,因为它强制回发。所以最好的方法是使用隐藏域:
One suggestion is using hiddenfiled as shown below.
一个建议是使用 hiddenfiled ,如下所示。
<script type="text/javascript">
function Foo(){
var hidden=document.getElementById('hidValue');
hidden.value="test";
}
</script>
On aspx:
在aspx上:
In code behind
在后面的代码中
protected HtmlControls.HtmlInputHidden hidValue;
protected void Page_Load(object sender, System.EventArgs e)
{
dynamic hiddenValue = hidValue.Value;
}
NB: you can use asp:HiddenFieldas well
注意:您可以使用ASP:HiddenField以及
回答by Ronak Patel
you can use AJAX for partial postback i.e. without refreshing the whole page
您可以使用 AJAX 进行部分回发,即无需刷新整个页面
e.g. using jquery ajax
例如使用 jquery ajax
$.ajax({
url: 'default.aspx',
data: 'data1=value1&data2=value2&data3=value3',
type: 'POST',
success: function (resp) {
//request sent and response received.
}
});
above code will make reequest to your default.aspx page and pass the data which you can access as below in codebehind
上面的代码将请求您的 default.aspx 页面并传递您可以在代码隐藏中访问的数据,如下所示
string value1 = Request["data1"].ToString();