简体   繁体   中英

AJAX call method on another page

I have a list, and when I click a row on that list, I have AJAX syntax that passes an ID to a method in the code behind, and returns the data to some html elements. This works fine, but right now it returns the data to html elements that are on the same page. What if I wanted to have it navigate to another page to display the data? So here is my current code:

My aspx page

<%@ Page Language="C#" AutoEventWireup="true" 
CodeFile="listPage.aspx.cs" Inherits="listPage" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">

<head runat="server">

<title>Call C# method/function using JQuery Ajax</title>

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<script type="text/javascript" language="javascript">
    $(document).ready(function () {
                $('#matchupTable tr').click(function () {
                    var gameID = $(this).attr('id');
                    //var gameID = '19';
                    $.ajax({
                        url: 'listPage.aspx/GetMatchupByID',
                        method: 'post',
                        contentType: "application/json",
                        data: '{gameID:' + gameID + '}',
                        dataType: "json",
                        success: function (data) {
                            $('#awayCity').text(data.d.AwayCity);
                            $('#awayTeam').text(data.d.AwayTeam);
                            $('#home').text(data.d.Away);
                            $('#homeCity').text(data.d.HomeCity);
                            $('#homeTeam').text(data.d.HomeTeam);
                            $('#home').text(data.d.Home);
                        },
                        error: function (err) {
                            alert(err);
                        }
                    });
                });
            });
</script>

</head>
<body>
    <%-- LIST AREA --%>
    <form id="form1" runat="server">
    <div>
    <table id="matchupTable">
        <tr  style="cursor: pointer;" id="25"><td>Click me, I won't hurt you</td></tr>
    </table>
</div>
</form>

<%-- RESULTS AREA --%>
<div id="awayTeamDiv">
    <div id="awayTeamTitle">
        <h5 id="awayCity"></h5>
        <h3 id="awayTeam"></h3>
        <p id="away"></p>
    </div>
</div>
<div id="homeTeamDiv">
    <div id="homeTeamTitle">
        <h5 id="homeCity"></h5>
        <h3 id="homeTeam"></h3>
        <p id="home"></p>
    </div>
</div>

</body>
</html>

My code behind

using System;
using System.Web.Services;
using GamblersDenNet;
using System.Data;
using System.Data.SqlClient;

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

    }

    [WebMethod]
    public static Matchup GetMatchupByID(int gameID)
    {
        Matchup matchup = new Matchup();

        SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["TrinoviContext"].ConnectionString);

        con.Open();
        SqlCommand cmd = new SqlCommand("usp_GetMatchupDetails", con);
        cmd.CommandType = CommandType.StoredProcedure;
        cmd.Parameters.Add(new SqlParameter()
        {
            ParameterName = "@GameID",
            Value = gameID
        });
        SqlDataReader reader = cmd.ExecuteReader();
        while (reader.Read())
        {
                matchup.GameID = reader["GameID"].ToString();
                matchup.Date = reader["Date"].ToString();
                matchup.HomeCity = reader["HomeCity"].ToString();
                matchup.HomeTeam = reader["HomeTeam"].ToString();
                matchup.Home = reader["Home"].ToString();
                matchup.AwayCity = reader["AwayCity"].ToString();
                matchup.AwayTeam = reader["AwayTeam"].ToString();
                matchup.Away = reader["Away"].ToString();
        }
        return matchup;
    }
}

So, if I wanted to instead have a detailsPage.aspx, and when I clicked the tr element, it redirected to this detailsPage.aspx and executed the code, what would that look like? I know I'd have to move my div elements in the RESULTS AREA of my listPage.aspx to the other page, and maybe set that stored procedure to execute on page load, but how would I pass it the parameter from the row I clicked? What would that look like?

In the interest of brevity I removed some extraneous code, so I'm sorry if there may be some syntax errors in my example.

Thanks all!

Try to just make a normal http post request rather than an ajax and have your endpoint GetMatchupByID return a view with your object Matchup as the view model .

See this link for returning a view and passing a view model to it: https://docs.microsoft.com/en-us/aspnet/mvc/overview/older-versions-1/getting-started-with-mvc/getting-started-with-mvc-part3#passing-a-viewmodel

My solution to this problem was to use pass the value using a query string:

$('#matchupTable tr').click(function () {
            var gameID = '/detailsPage.aspx?gameID=' + $(this).attr('id');
            window.location.href = gameID;
 });

and then on the Page_Load of detailsPage, I moved the code of GetMatchupByID(), and passed it the parameter by using:

 string GameID = Request.QueryString["gameID"];

 SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["TrinoviContext"].ConnectionString);

  con.Open();
  SqlCommand cmd = new SqlCommand("usp_GetMatchupDetails", con);
  cmd.CommandType = CommandType.StoredProcedure;
  cmd.Parameters.AddWithValue("@GameID", GameID);
  SqlDataReader reader = cmd.ExecuteReader();
  while (reader.Read())
      {
          // populate properties I need for display on page
      }
  con.Close();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM