user2423434
user2423434

Reputation: 199

pass the values from javascript to Codebehind

I am new to ASP.NET

I want to implement the website about..

  1. draw(add) some points. (the number of points: depend on user★)
  2. user move these points within gray box
  3. 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..

  1. how to pass some values to codebehind part without reload pages.

  2. 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/)

<%@ 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>

Upvotes: 3

Views: 30630

Answers (3)

Anthony Horovitz
Anthony Horovitz

Reputation: 186

You need to use AJAX for this.

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

Much better way to send data is through POST because GET is limited to around 2000 characters.

Also, better way to format your data points would be through JSON. What I’ve shown below is not the best practice really ;)

<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

ASP .NET Ajax examples for the beginner

Upvotes: 2

Ronak Patel
Ronak Patel

Reputation: 2610

you can use AJAX for partial postback i.e. without refreshing the whole page

e.g. using 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

string value1 = Request["data1"].ToString();

Upvotes: 3

Saritha.S.R
Saritha.S.R

Reputation: 800

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:

One suggestion is using hiddenfiled as shown below.

<script type="text/javascript">
    function Foo(){
        var hidden=document.getElementById('hidValue');
        hidden.value="test";
    }
</script>

On 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:HiddenField as well

Upvotes: 0

Related Questions