I'm having trouble in my MVC web application in trying to pass information to/from the controller and view. Namely, in my view, I have two text fields that I would like to pass information from to a method in my controller, then return the respective result back to the JavaScript so that it can make the appropriate changes to the page.
//C# Controller File
using LiquipediaScraper.Models;
using Microsoft.AspNetCore.Mvc;
using System.Diagnostics;
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Extensions.Logging;
using HtmlAgilityPack;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using System.Net;
using System.Text;
using System.IO;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Web;
namespace LiquipediaScraper.Controllers
{
//the method I'm trying to access and interact with.
public string GetInfo(string teamName)
{
string teamUrl = ("liquipedia.net/overwatch/" + teamName);
var response = CallUrl(teamUrl).Result;
if(response != null)
{
List<List<string>> players = ParseHtmlForPlayers(response);
List<Player> playerList = new List<Player>();
for(int i = 0; i < players[0].Count; i++)
{
Player newPlayer = new Player();
newPlayer.Tag = players[0][i];
newPlayer.Role = players[1][i];
playerList.Add(newPlayer);
}
string jsonPlayers = JsonSerializer.Serialize(playerList);
Console.WriteLine(jsonPlayers);
return jsonPlayers;
}
else
{
return null;
}
}
}
Javascript here:
document.getElementById("updateTeams").addEventListener("click", function () {
var team1 = document.getElementById("team1Name").value;
var team2 = document.getElementById("team2Name").value;
document.getElementById("updateTeams").parentElement.insertAdjacentHTML('beforeend', ("<p>" + team1 + "<p>"));
//var jsonPlayers = <%#LiquipediaScraper.LiquipediaScraper.Controllers.getInfo(team1) %>; didnt work
//user insertAdjacentHTML to insert the players and avoid breaking
//the salami lid dont fit
//ajax doesn't work
$.ajax({
type: "POST",
url: '.../Controllers/HomeController.cs/GetInfo',
data: team1,
dataType: "json",
success: function (msg) {
$("#divResult").html("success");
},
error: function (e) {
$("#divResult").html("Something Wrong.");
}
});
});
I don't fully understand if AJAX is the solution to my problem here, and if so, how to actually implement it. I have also tried using [WebMethod] but my solution wouldn't let me reference System.Web.Services (saying that it didn't exist). My only other thought is that I have a fundamental misunderstanding of where in the MVC setup I should have this function, as theoretically I could include it in the javascript for the webpage.