Struggling in my MVC web application with passing information between the controller and view. Specifically, I have two text fields in the view that I want to send information from to a method in the controller, then receive the result back in JavaScript to update the page accordingly.
//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 below:
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'm unsure if AJAX is the right solution for my issue, and if it is, how to implement it correctly. I also attempted to use [WebMethod] but encountered issues referencing System.Web.Services. My only other idea is that I may not be placing this function in the right location within the MVC setup, as theoretically, I could include it in the webpage's JavaScript.