locked
Select event with codebehind RRS feed

  • Question

  • User-284642143 posted

    I have a webform which captures the date from the user (Jquery Datepicker). I then have a select event for the datepicker

    <script>
        $("input[id$=Textbox1]").datepicker({
            onSelect: function (dateText, inst) {
                var date = $(this).val();
                var time = $('#time').val();
                alert('on select triggered');
                $("#start").val(date + time.toString(' HH:mm').toString());
            }
        });
    </script>

    When they select a date i would like to have some codebehind run and get data from a database and then populate another control with that data.

    How could i tie the above event with codebehind?

    Thursday, January 31, 2019 5:05 PM

Answers

  • User475983607 posted

    Add a WebMethod to the page and add an AJAX call call the Web Method.

    <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="AjaxDemo.aspx.cs" Inherits="WebFormsDemo.AjaxDemo" %>
    
    <!DOCTYPE html>
    
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
        <title></title>
        <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css" />
        <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>
    </head>
    <body>
        <form id="form1" runat="server">
            <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
            <div id="result">
            </div>
        </form>
        <script>
    
            $("#<%= TextBox1.ClientID%>").datepicker({
                onSelect: function (dateText, inst) {
                    var data = {
                        date: $(this).val()
                    };
    
                    $.ajax({
                        type: "POST",
                        url: '/AjaxDemo.aspx/GetData',
                        data: JSON.stringify(data),
                        dataType: 'json',
                        contentType: "application/json; charset=utf-8",
                    }).done(function (data) {
                        console.log(data);
                        //write the response
                        $('#result').text(data.d);
                    });
                }
            });
        </script>
    </body>
    </html>
    
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Threading;
    using System.Web;
    using System.Web.Script.Services;
    using System.Web.Services;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    
    namespace WebFormsDemo
    {
        public partial class AjaxDemo : System.Web.UI.Page
        {
            protected void Page_Load(object sender, EventArgs e)
            {
    
            }
    
            [WebMethod]
            public static string GetData(DateTime date)
            {
                return $"You selected {date}.";
            }
    
        }
    }

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, January 31, 2019 6:02 PM
  • User-1174608757 posted

    Hi EssCee,

    According to your description,in asp.net you could create a Web Service (asmx) file to call the web method. Here is a demo ,I hope it could help you.

    aspx:

     <script>
            $(function () {
                var a = $("#TextBox1").val();
                var o = { "name": a }
                $("#Button1").click(function () {
                    $.ajax({
                        type: "POST",
                        url: "WebService1.asmx/GetDat",
                        contentType: "application/json; charset=utf-8",
                        dataType: "json",
                        data: JSON.stringify(o),
                        success: function (msg) { alert(msg.d) }
                  
    
                    })
                
    
                })
               
            })
        </script>
    </head>
    <body>
        <form id="form1" runat="server">
            <div>
                <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
                <asp:Button ID="Button1" runat="server" Text="Button" />
            </div>
        </form>
    </body>
    </html>

    In Web Service file(.asmx)

      [WebService(Namespace = "http://tempuri.org/")]
        [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
        [System.ComponentModel.ToolboxItem(false)]
        // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
        [System.Web.Script.Services.ScriptService]
        public class WebService1 : System.Web.Services.WebService
        {
    
            [WebMethod]
            public string GetDat(string name )
            {
                return name;
            }
        }

    Else you could use Generic Handler(.ashx) to solve the ajax request.Here is a demo,

    aspx:

    <script>
            $(function () {
                var a = $("#TextBox1").val();
                var o = { "name": a }
                $("#Button1").click(function () {
                    $.ajax({
                        type: "POST",
                        url: "Handler1.ashx",
                        data: { name: a },
                       dataType: "json",
                       success: function (response) {
                       alert(response.d);
                }
            });
    
                })
               
            })
        </script>

    ashx file:

    public class Handler1 : IHttpHandler
        {
    
            public void ProcessRequest(HttpContext context)
            {
                context.Response.ContentType = "text/plain";
                string name = context.Request.Form["name"]; // get the data from aspx
                var wrapper = new { d = name };
                context.Response.Write(JsonConvert.SerializeObject(wrapper)); // return json file
            }
    
            public bool IsReusable
            {
                get
                {
                    return false;
                }
            }
        }

    Best Regards

    Wei Zhang

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Friday, February 1, 2019 6:03 AM

All replies

  • User475983607 posted

    Add a WebMethod to the page and add an AJAX call call the Web Method.

    <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="AjaxDemo.aspx.cs" Inherits="WebFormsDemo.AjaxDemo" %>
    
    <!DOCTYPE html>
    
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
        <title></title>
        <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css" />
        <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>
    </head>
    <body>
        <form id="form1" runat="server">
            <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
            <div id="result">
            </div>
        </form>
        <script>
    
            $("#<%= TextBox1.ClientID%>").datepicker({
                onSelect: function (dateText, inst) {
                    var data = {
                        date: $(this).val()
                    };
    
                    $.ajax({
                        type: "POST",
                        url: '/AjaxDemo.aspx/GetData',
                        data: JSON.stringify(data),
                        dataType: 'json',
                        contentType: "application/json; charset=utf-8",
                    }).done(function (data) {
                        console.log(data);
                        //write the response
                        $('#result').text(data.d);
                    });
                }
            });
        </script>
    </body>
    </html>
    
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Threading;
    using System.Web;
    using System.Web.Script.Services;
    using System.Web.Services;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    
    namespace WebFormsDemo
    {
        public partial class AjaxDemo : System.Web.UI.Page
        {
            protected void Page_Load(object sender, EventArgs e)
            {
    
            }
    
            [WebMethod]
            public static string GetData(DateTime date)
            {
                return $"You selected {date}.";
            }
    
        }
    }

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, January 31, 2019 6:02 PM
  • User-284642143 posted
    Thanks!! Would it be appropriate to create a web method within the same webform page? Or could this be separated to another class and the webform could be used to call that method?
    Thursday, January 31, 2019 9:48 PM
  • User475983607 posted

    Would it be appropriate to create a web method within the same webform page?

    That's what I do.

    Or could this be separated to another class and the webform could be used to call that method?

    Sure you could add an ASMX service to the project.  

    Thursday, January 31, 2019 9:54 PM
  • User-1174608757 posted

    Hi EssCee,

    According to your description,in asp.net you could create a Web Service (asmx) file to call the web method. Here is a demo ,I hope it could help you.

    aspx:

     <script>
            $(function () {
                var a = $("#TextBox1").val();
                var o = { "name": a }
                $("#Button1").click(function () {
                    $.ajax({
                        type: "POST",
                        url: "WebService1.asmx/GetDat",
                        contentType: "application/json; charset=utf-8",
                        dataType: "json",
                        data: JSON.stringify(o),
                        success: function (msg) { alert(msg.d) }
                  
    
                    })
                
    
                })
               
            })
        </script>
    </head>
    <body>
        <form id="form1" runat="server">
            <div>
                <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
                <asp:Button ID="Button1" runat="server" Text="Button" />
            </div>
        </form>
    </body>
    </html>

    In Web Service file(.asmx)

      [WebService(Namespace = "http://tempuri.org/")]
        [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
        [System.ComponentModel.ToolboxItem(false)]
        // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
        [System.Web.Script.Services.ScriptService]
        public class WebService1 : System.Web.Services.WebService
        {
    
            [WebMethod]
            public string GetDat(string name )
            {
                return name;
            }
        }

    Else you could use Generic Handler(.ashx) to solve the ajax request.Here is a demo,

    aspx:

    <script>
            $(function () {
                var a = $("#TextBox1").val();
                var o = { "name": a }
                $("#Button1").click(function () {
                    $.ajax({
                        type: "POST",
                        url: "Handler1.ashx",
                        data: { name: a },
                       dataType: "json",
                       success: function (response) {
                       alert(response.d);
                }
            });
    
                })
               
            })
        </script>

    ashx file:

    public class Handler1 : IHttpHandler
        {
    
            public void ProcessRequest(HttpContext context)
            {
                context.Response.ContentType = "text/plain";
                string name = context.Request.Form["name"]; // get the data from aspx
                var wrapper = new { d = name };
                context.Response.Write(JsonConvert.SerializeObject(wrapper)); // return json file
            }
    
            public bool IsReusable
            {
                get
                {
                    return false;
                }
            }
        }

    Best Regards

    Wei Zhang

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Friday, February 1, 2019 6:03 AM