How to run an event in Codebehind being called by jQuery?

Asked

Viewed 423 times

0

I have this code in Aspx:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Index.aspx.cs" Inherits="WebSite.View.Index" %>

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <script src="Scripts/jquery-3.4.1.min.js"></script>
    <title>Projeto para Testes</title>
</head>
<body>
    <form id="form1" runat="server">
        <div id="dvEventos" class="dvEventos">
            <h1>Apenas um teste</h1>
            <asp:Button ID="btnEventoCsharp" CssClass="btnEventoCsharp" Text="Evento C#" OnClick="btnEventoCsharp_Click" runat="server" />
            <asp:Button ID="btnEventoCsharpByJS" CssClass="btnEventoCsharpByJS" Text="Evento C# by JS" OnClick="btnEventoCsharpByJS_Click" runat="server"  />
            <button id="btnEventoJqueryClick" class="btnEventoJqueryClick">Evento C# by Jquery</button>
            <button id="btnEventoJquery" class="btnEventoJquery">Evento Jquery</button>
        </div>
    </form>
</body>
<script>
    $(document).ready(function () {
        CarregaEventosIndex();
    });

    function CarregaEventosIndex() {
        $('.btnEventoJquery').off('click').on('click', function () {
            alert('Event click by Jquery');
        });

        $('.btnEventoJqueryClick').off('click').on('click', function () {
            $("input[id*=btnEventoCsharpByJS]").click();
        });
    }
</script>
</html>

The file of mine Codebehind:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace WebSite.View
{
    public partial class Index : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void MetodoSemParametroChamadoEventosDiferentes()
        {
            string passeiAqui = "sem parametro";
            string evento = passeiAqui;
        }

        /// Evento de Teste
        protected void btnEventoCsharpByJS_Click(object sender, EventArgs e)
        {
            MetodoSemParametroChamadoEventosDiferentes();
        }
    }
}

I am using Webforms, and I need to call a Codebehind event by jQuery, in case, using this button btnEventoJqueryClick. But there’s a catch, if I use that code $("input[id*=btnEventoCsharpByJS]").click(); through the browser console, using breakpoint in Codebehind realize that the event is called, but clicking the button is not being called the event. What am I doing wrong? Or, how can I call a Codebehind event by jQuery differently?

  • Looking at the browser console, does any "network" request appear? I created an example here, exactly how you put it there and this working.

  • To run anything that is on the server side by the browser, you will need to make a request for it, a GET or POST for example.

  • Helped you to solve?

  • I managed using another solution

1 answer

0

To solve this question ask a <input type="hidden" /> same example below:

<input type="hidden" name="__EVENTTARGET" id="__EVENTTARGET" value="" />
<input type="hidden" name="__EVENTARGUMENT" id="__EVENTARGUMENT" value="" />

within the tag <form></form>, these two input will serve to let the server know what to do, and if you have any argument to pass that also has it to execute any method in the codebehind, all the request in this case is with the verb POSTwhich is the standard.

The page .aspx has the following result:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Test.aspx.cs"
    Inherits="WebApplication1.Test"%>

<!DOCTYPE html>    
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
  <title></title>
  <script src="Scripts/jquery-3.4.1.js"></script>
</head>
<body>
  <form id="form1" runat="server">
    <input type="hidden" name="__EVENTTARGET" id="__EVENTTARGET" value="" />
    <input type="hidden" name="__EVENTARGUMENT" id="__EVENTARGUMENT" value="" />     
    <button id="btnDateTime">Evento Data e Hora</button>    
    <div>      
      <asp:Literal ID="TxtDataNow" runat="server"></asp:Literal>
    </div>
  </form>
  <script>
    function __doPostBack(eventTarget, eventArgument) {
      const theForm = document.getElementById("form1");
      if (!theForm.onsubmit || (theForm.onsubmit() != false)) {
        theForm.__EVENTTARGET.value = eventTarget;
        theForm.__EVENTARGUMENT.value = eventArgument;
        theForm.submit();
      }
    }
    $(document).ready(function () {
      $("#btnDateTime").click(function () {
        __doPostBack('btnDateTime', '');
      });
    });
  </script>
</body>
</html>

A code has been created in javascript by the name of __doPostBack which has the actual intention of sending the information to your back-end and action information and arguments if necessary.


In the code of this page would have some modifications where you need to know which button was clicked and what is to be done, in case __EVENTTARGET is the name of the button that was clicked and in this case triggers the method ActionBtn() by changing the value of <Literal>:

public partial class Test : System.Web.UI.Page
{
  protected void Page_Load(object sender, EventArgs e)
  {
     if (Page.IsPostBack)
     {
        var __EVENTTARGET = Request.Form["__EVENTTARGET"];
        if (__EVENTTARGET == "btnDateTime")
        {
           ActionBtn();
        }
     }
  }
  protected void ActionBtn()
  {
     TxtDataNow.Text = DateTime.Now.ToString(@"dd/MM/yyyy HH\:mm\:ss");
  }
}

I don’t know how much it needs to be done like this, when I used this style I never did anything like it, at most when it was a Webservice with a method static to bring information to the Front, have to check if this really is necessary, maybe in certain rare cases yes, but mostly a simple component with its normal event of PostBack already solves the problem.

In this example is used a button normal, because, most examples are linked to components belonging to toolbox for his event to be redone in another way, in which he does not actually do the event. If you have a problem with the Eventvalidation include a configuration at the beginning of the page in the first line: <%@ Page EnableEventValidation="false" ....

References:

Browser other questions tagged

You are not signed in. Login or sign up in order to post.