0

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.

  • Check your URL value in your ajax call: it needs to be /Home/GetInfo. Also, make sure GetInfo method is an HttpPost method. See this link for help: https://stackoverflow.com/questions/16186083/making-a-simple-ajax-call-to-controller-in-asp-net-mvc – SoftwareDveloper Aug 19 '23 at 18:47
  • change `url: '.../Controllers/HomeController.cs/GetInfo',` to `url: '/Home/GetInfo` – sairfan Aug 21 '23 at 02:44

1 Answers1

0

There are a few things you have to worry about, First of all, your controller code doesn't seem to be right.

public class HomeController : Controller 
{
   [HttpPost]
   [Route("home/create")]
   public async Task<ActionResult> Create([FromBody] CreateRequest createRequest)
   {
      //your logic
   }

}

And also in your ajax content your URL is wrong. Since it is a MVC project you can use something like this

var request= JSON.stringify({ 'createRequest': createObject });

        $.ajax({
            type: 'POST',
            dataType: 'JSON',
            url: '/home/create',
            data: createObject,
            success: function (response) {

                var jsonResponse = JSON.stringify(response);
                var parsedResponse = JSON.parse(jsonResponse);
            }
        });