0

I have an html table in my asp.net application. When a td element is clicked, I store that value in a hidden field using JavaScript.

function rebind() {
        $('.window td').on('click', function () {
            var idName = this.id;
            var selectedid = idName.substring(1);
            console.log(selectedid);
            $('#hidden').val(selectedid);
         });
      }

Now, I want to reload this aspx page after this click event because I need new data to be displayed as per the td value and I also want to preserve this hidden field value after reload or refresh and I want to use it on server side (aspx.cs).

I've tried ajax like this,

$.ajax({
        url: "Default.aspx",
        data: selectedid,
        type: "POST",
        success: function (result) {
            alert('Yay! It worked!');
        },
        error: function (result) {
            alert('Error');
        }
    });

But I am not able to access selectedid variable on c# side. I want to know if I am going in the right direction?

nrvbha
  • 139
  • 4
  • 19
  • 2
    If you plan on refreshing the whole page you might need to set a cookie with the value. Other option can be to load data with ajax instead of refreshing the whole page. – Spokey Feb 04 '15 at 14:27
  • 1
    Cookies, localStorage or an AJAX request to a server side resource which saves/retrieves from a database of some variety. – Rory McCrossan Feb 04 '15 at 14:27
  • possible duplicate of [Hidden value assigned in js lost after postback](http://stackoverflow.com/questions/6270085/hidden-value-assigned-in-js-lost-after-postback) – Cᴏʀʏ Feb 04 '15 at 14:32
  • @RoryMcCrossan better to use sessionStorage than localStorage, localStorage is cleared after browser close, sessionStorage after tab closed. – mybirthname Feb 04 '15 at 14:35
  • you may be able to find some answers here: http://stackoverflow.com/search?q=javascript+persist – Dan Beaulieu Feb 04 '15 at 14:51
  • Maybe this will help you : https://github.com/marcuswestin/store.js/ – Alarid Feb 04 '15 at 14:52
  • 2
    I see you edited your question to show an AJAX attempt. However, you're just posting to the page. You should instead post to an ASP.NET Web API (instead of using the code behind, your server side code will be in a Web API Controller). – mason Feb 04 '15 at 14:52
  • If I use localStorage or sessionStorage, how do I serialize that data back to c#? I need the variable on server side. – nrvbha Feb 04 '15 at 15:14

1 Answers1

0
<input type="hidden" id="MyHiddenField" name="MyHiddenField" />
<button type="button" onclick="setHiddenValue();">Set Hidden Value</button>
<br />
<asp:Button runat="server" Text="Cause Postback" OnClick="PostBackBtn_Click" />
<br />   
<asp:Label ID="ResultLbl" Text="No result yet, hit Set Hidden Value then Cause Postback." runat="server" />
<script type="text/javascript">
    function setHiddenValue() {
        $("#MyHiddenField").val("Hello, world!");
    }
</script>

And code behind:

protected void PostBackBtn_Click(object sender, EventArgs e)
{
    var value = Request.Form["MyHiddenField"];
    //do something with value
    ResultLbl.Text = value;
}

You can see that now we've retrieved the value on the server side and use it to set a label with the value upon postback. You could use another hidden value to pass the value back to JS instead of using a Label.


Alternatively, use AJAX with ASP.NET Web API. This has the advantage that the page doesn't reload. You can send your value to a controller, and have the server return some updated data. This is great for bandwidth, since only the data that we absolutely need to send back and forth will actually be sent. And we don't have to worry about losing the JavaScript variables since the page never reloads, and the user doesn't get the "postback flicker".

$.ajax({
    url: "api/Products/GetAllProductsForCategory?categoryId=" + $("#MyHiddenField").val);
    type: "GET"
})
.done(function(data){
    alert("received data: " + data);
    //now we'd turn the data into HTML and add it to the DOM
    });

ASP.NET Web API

public class ProductsController : ApiController
{
    public IEnumerable<Product> GetAllProductsForCategory(string categoryId)
    {
        return products.Where(p => p.Category == categoryId);
    }
}
mason
  • 31,774
  • 10
  • 77
  • 121
  • Why do I need to use ASP.Net Web API? Why can't I send the data to an aspx.cs page? – nrvbha Feb 04 '15 at 16:09
  • Because `WebMethod` and `PageMethod` are no longer supported, and ASP.NET Web API is supported, and it has a cleaner usage model that promotes proper Separation of Concerns. – mason Feb 04 '15 at 16:11
  • Actually, I've never used ASP.NET Web API and I need the sent value to be passed as a parameter to a method in my aspx.cs page. Do I need to use HttpClient to call web api from code behind? – nrvbha Feb 04 '15 at 16:15
  • @nrvbha I provided two different ways of doing this. If you read the first part of my answer, I do explain how to do exactly that. The second answer is my attempt at getting you to switch to a newer architecture. It certainly isn't required and I can understand a new framework appears daunting at first, but I did provide a link to Microsoft's documentation which includes tutorials explaining it. – mason Feb 04 '15 at 16:17
  • Yes. I understand. For the first part, unfortunately I can't create a new button. When the html td element is clicked, postback should happen and the value must be transferred from client side to server side. That is why I though of using location.reload but it does not preserve the value in hidden field. – nrvbha Feb 04 '15 at 16:32
  • @nrvbha You don't have to use a button. You can force a postback from JavaScript, and grab the form values in the Page_Load method. – mason Feb 04 '15 at 16:33
  • Yes. That is exactly what I want to do. But unfortunately I do not know how. Please help. – nrvbha Feb 04 '15 at 16:34
  • @nrvbha Then obviously you haven't put enough research effort into this, as a simple Google search reveals plenty of options, including [this one](http://stackoverflow.com/questions/1305954/asp-net-postback-with-javascript). – mason Feb 04 '15 at 16:36