Search code examples
c#jqueryasp.netjquery-ui-slider

Pass Slider Values from jQuery to Code Behind


I am using ASP.NET with C# as Code Behind. The thing is, I've put a jQuery Slider in my code but I can't get the values from the slider into C# (already looked everywhere on the web) and I need them because the Slider Values must act as filters for the project I am doing (a web where you can buy products). I know you can't get the values directly from jQuery to C#, but I've tried passing them to ASP.NET and still seems inaccessible.

  <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
  <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
  <script>
      $(function () {
          $("#slider-range").slider({
          range: true,
          min: 0,
          max: 3000,
          values: [ 50, 500 ],
          slide: function( event, ui ) {
              $("#amount").val(ui.values[0] + "€ - " + ui.values[1] + "€");      
      }
          });

        $( "#amount" ).val($( "#slider-range" ).slider( "values", 0 ) +
            "€ - " + $("#slider-range").slider("values", 1) + "€");
      } );
  </script>
<p>
  <asp:Label for="amount" runat="server">Precio:</asp:Label>
  <input type="text" id="amount" readonly style="border:0; color:#f6931f; font-weight:bold;">
</p>


<div id="slider-range">
</div>

Now, here it is what it looks like:

image

"amount" just showcases the values of the slider in the "Precio" Label. I need a variable and pass it to ASP then to C#, how can I do it?

So basically, when I hit the button marked in red I want to get both the minimum and maximum selected values in C#, because I have to pass them to the different layers of the project.

I have already tried using a hidden type on asp to put the jQuery values in it, but when I try to get the values from the hidden type in C# I just get nulls.


Solution

  • To pass data from javascript to code behind, you can put the data in an element known by the code-behind, that means the element, e.g. an hidden field:

    <asp:HiddenField ID="myValueField" ClientIdMode='STATIC' runat="server" />
    

    Put the values in it like you did in your post:

    $("#myValueField").val(ui.values[0] + "€ - " + ui.values[1] + "€");
    

    Make sure, the Hidden Field is inside your Page-Form-Control and your button is causing an server-side postback.