admin管理员组

文章数量:1357109

I'm writing a ASP.NET application.

I have a page, where user will select or deselect some elements. This happens client-side: when user clicks on a div, javascript function is called and some classes are changed, so the div is "grayed out".
There is also a Save button (asp:Button), that will save data.

What is the best way to pass information about selected elements back to server-side?

I have tried to put that info in cookies. Each div has ID, so I would create cookie with that ID and boolean value. This is a bad idea, because:
- when user (de-)selects some elements, and then navigates away from page without saving
- then navigates back, and without selecting anything clicks "Save", cookies have previous values and that gets saved.

I'm writing a ASP.NET application.

I have a page, where user will select or deselect some elements. This happens client-side: when user clicks on a div, javascript function is called and some classes are changed, so the div is "grayed out".
There is also a Save button (asp:Button), that will save data.

What is the best way to pass information about selected elements back to server-side?

I have tried to put that info in cookies. Each div has ID, so I would create cookie with that ID and boolean value. This is a bad idea, because:
- when user (de-)selects some elements, and then navigates away from page without saving
- then navigates back, and without selecting anything clicks "Save", cookies have previous values and that gets saved.

Share Improve this question asked Feb 4, 2014 at 8:29 TschareckTschareck 4,24912 gold badges49 silver badges79 bronze badges 2
  • can you update your question with the code you have tried ? – SpiderCode Commented Feb 4, 2014 at 8:55
  • have a look at my answer. Hope you get the solution for your query. Don't forget to upvote and mark it as an answer. – SpiderCode Commented Feb 4, 2014 at 14:03
Add a ment  | 

4 Answers 4

Reset to default 3

What you have tried is good except Cookies. I can understand the problem you are facing. So I would suggest to use Hidden Field instead of Cookies.

When your div is get selected call the javascript function and store the value (in specific format) in hidden field. and In the same way when your div is deselected remove the value from the HiddenField.

You can store value in HiddenField in below format (ID:value) :

div1:true;div2:true;div3:true

Now on the click event of the button you can first split the values by semicolon (';') and you will get the array like this :

  1. div1:true,
  2. div2:true,
  3. div3:false

for each value again split the value by colon (':') and you will get the div id at the 0th index and its value on first index.

So basically your code to get the values from hidden field and perform an action on it would be as mentioned below :

foreach (var selectedDiv in this.hfSelected.Value.Split(';'))
{
    var divId = selectedDiv.Split(':')[0];
    var divValue = selectedDiv.Split(':')[1];

    // Perform action on divId and divValue
}

Update :

To store the value in HiddenField, instead of div click, you can use the OnClientClick event of the button and get the value of selected and deselected div. See my below code sample :

ASPX Page :

<html xmlns="http://www.w3/1999/xhtml">
<head runat="server">
    <title></title>
    <script type="text/javascript" src="Scripts/jquery-1.8.2.js" language="javascript"></script>
    <script type="text/javascript" src="Scripts/jquery-1.8.2.min.js" language="javascript"></script>
    <script type="text/javascript" src="Scripts/jquery-ui-1.9.1.custom.js" language="javascript"></script>
    <script type="text/javascript" src="Scripts/jquery-ui-1.9.1.custom.min.js" language="javascript"></script>
    <style type="text/css">
        .selectedDiv {
            background-color: #333;
            color: #fff;
            height: 30px;
            width: 100%;
        }

        .deselectedDiv {
            background-color: #bababa;
            color: #000;
            height: 30px;
            width: 100%;
        }
    </style>
</head>
<body>
    <form id="form1" runat="server">
        <div class="selectedDiv" id="div1">I am Div 1</div>
        <div class="selectedDiv" id="div2">I am Div 2</div>
        <div class="selectedDiv" id="div3">I am Div 3</div>
        <div class="selectedDiv" id="div4">I am Div 4</div>
        <div class="selectedDiv" id="div5">I am Div 5</div>

        <input type="hidden" id="hfDivSelection" runat="server" />

        <asp:Button runat="server" ID="buttonSave" OnClick="buttonSave_OnClick"  Text ="Save" OnClientClick="GetSelection()"/>
    </form>
     <script type="text/javascript">
         $('div').click(function () {
             var css = $(this).attr('class');

             if (css == 'selectedDiv') {
                 $(this).attr('class', 'deselectedDiv');
             } else {
                 $(this).attr('class', 'selectedDiv');
             }

         });

         function GetSelection() {
             $('div').each(function() {
                 var values = $('#<%=hfDivSelection.ClientID%>').val();
                 var css = $(this).attr('class');
                 var divId = $(this).attr('id');
                 if (css == 'selectedDiv') {
                     $('#<%=hfDivSelection.ClientID%>').val(values + divId + ':true;');
                 } else if (css == 'deselectedDiv') {
                     $('#<%=hfDivSelection.ClientID%>').val(values + divId + ':false;');
                 }
             });
         }
    </script>
</body>
</html>

Code Behind :

protected void buttonSave_OnClick(object sender, EventArgs e)
{
    foreach (var selectedDiv in this.hfDivSelection.Value.Split(';'))
    {
        var divId = selectedDiv.Split(':')[0];
        var divValue = selectedDiv.Split(':')[1];

        // Perform action on divId and divValue
    }
}

I remend the $.ajax function of jquery. It is very convenient.

Here is an example.

Javascript + jquery code:

//this $.ajaxSetup step is optional, but will save you a bunch of caching and asynchrony problems.
$.ajaxSetup({
  cache: false,
  async: false
});

$.ajax({
    type: "POST",
    url: 'submit.aspx',
    data: {"field1": "value1", "field2": "value2"},
    dataType: 'json',
    success: function(response){console.log('Data submit worked. Response was:\n' + response)}
});

(More info on this function at http://api.jquery./jQuery.ajax/.)


Then, in submit.aspx, place your code to get the info, this SO article may help.

You can then save the data to an xml file via asp. When you want to reload the user's settings, you can use the GET mand of the $.ajax function:

$.ajax({
    type: "GET",
    url: '/data/userfields.xml',
    dataType: "xml",

    success: function(xml) {
        var fieldvalue = $(xml).find('a_node').attr('an_attrib');
        //...
    },
    error: function(xml) { console.log ('failed to get xml file on import of file: /data/userfields.xml');}
});

In my opinion the best thing would be to use checkboxes (placed in a form that will be submited on button click) and use CSS to stile the div's accordig to the checkbox statuses.

I suggest using ajax callbacks. Using cookies on this approach is a bit messy. Create "on click" events on each div and if you really want to use a best practice approach to save data on the client side I suggest using Local Storage: http://www.w3schools./html/html5_webstorage.asp

Hope this helps

本文标签: javascriptPass data from client side to server sideStack Overflow