Experiencing difficulty with the communication between C# Controller and HTML/JavaScript View in the MVC framework

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.

Answer №1

There are a couple of key concerns to address here. Firstly, it appears that there may be an issue with your controller code.

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

}

Additionally, it seems that the URL in your ajax content is incorrect. In an MVC project, you should consider using a URL structure similar to the following

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);
            }
        });

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Ways to deactivate the submit button using Cookies, sessions, or local storage

Although cookies and storage can be deleted, they can still help prevent many human spammers who are unaware of this. How can I temporarily disable the form submit button on a specific page for just one day? I want to create a code that saves "Submitted" ...

Interacting with child collections data in C# through a RESTful API using Entity Framework context

Utilizing projection (explicit loading) to fetch and filter collection data from a child table via a RESTful Api service results in the JSON repeating the child table collections object. However, using the "AsNoTracking()" method eliminates the nested chil ...

In JavaScript programming, the function is always executed after the bottom code

I am currently working on a piece of code that is partially functional. The purpose of this code is to verify the existence of an email address in a database. If the email does not exist, it should return true; $(document).ready(function() { var ema ...

Executing functions within express - a mystery

I am struggling with a back-end JavaScript issue in Express. For some reason, when I call my function, it is returning undefined. Here's how it looks: // express route structure: exports.check = function(req, res) { // check if the username is prese ...

What is the process of encrypting a password using AngularJS on the client side, transferring it securely to the server through ExpressJS, and then decrypting it on the server

Looking for a simple method to encrypt a password on the client side using angular.js, send it to the server with express.js, and then decrypt it? While there are libraries like angular-bcrypt and similar ones in nodeJS, they may not be suitable as they ma ...

The module demoApp could not be instantiated because of an error stating that the module demoApp is not accessible

I am struggling to create a basic Single Page Application (SPA) using Angular and ngRoute/ngView. Unfortunately, I can't seem to get it to work properly. Every time I try, I encounter the error: angular.js:68 Uncaught Error: [$injector:modulerr] Fail ...

Error: Angular ng-file-upload successfully uploads file, but Node.js fails to receive it

Currently, I am working on loading and cropping a file using Angular. Many thanks to https://github.com/danialfarid/ng-file-upload SignUp2ControllerTest -- $scope.upload --> data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAMgAAADICAYAAACtWK6eAAAg ...

The functionality of WrapAll is not functioning properly in React JS

$('p').wrapAll($('<div class="wrapper"></div>')); .wrapper { background: #EEE; margin: 10px; padding: 5px; border: 1px solid black; } <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery. ...

Could someone break down for me the behavior exhibited within this method?

Hello there, I'm a beginner so please forgive me for any lack of knowledge. const example = { myFunction(){ console.log(this); }, myFunction2(){ function myFunction3(){ console.log(this) } return ...

Creating ellipses using Three.js with a specified list of points

Currently, I am working on a solar system model using Three.js. I have a function that calculates the position of the planet based on the day, but I am struggling to draw the correct elliptical orbit for the planet using a list of points generated from tha ...

Tips for boosting the efficiency of replaceWith on Internet Explorer 11

When rendering an array of data in a table element, there is a need for the table to be updated with new data as it can be filtered dynamically. However, I have encountered a performance issue specifically on IE11 when trying to render 1700 data entries us ...

Tips for transmitting one or multiple data using jquery.ajax

I found this code on stackoverflow and it is working well for uploading multiple files. However, I am facing an issue where I cannot send additional parameters along with the file upload. Despite trying various methods, I have been unsuccessful in sending ...

Error: Oops! The super expression can't be anything other than null or a function in JavaScript/TypeScript

I am facing an issue with class inheritance in my code. I have a class A that extends class B, which in turn extends class C. Whenever I try to create a new instance of class A within a function, I encounter the following error message: Uncaught TypeError: ...

Comparing the methods of retrieving JSP data in a servlet: using BufferedReader with request.getInputStream() versus using request.getParameter

Here is an example of my ajax call: $.ajax({ url: '/bin/commersenext/assetUpload', type: 'POST', contentType:'application/json', data: JSON.stringify(ob), dataType: ...

Error encountered while compiling a method within a .vue component due to a syntax issue

I have been closely following a tutorial on Vue.js app development from this link. The guide instructed me to add a login() function in the block of the Login.vue file. Here is the snippet of code provided: login() { fb.auth.signInWithEmailAndPa ...

Unusual behavior exhibited by JavaScript's eval() function

As part of my website design, I am developing custom Message Boxes that can display normal OK dialogs as well as Yes/No dialogs. These popups prompt the user to click either "OK" or "Yes/No", which then triggers corresponding callbacks executed using eval( ...

Ajax implementation for handling URL action parameters

I am currently facing challenges in passing data from a view to a controller using parameters. My goal is to pass these parameters when I select a row from a table and click on a button that triggers the ShowTasks() function. Here is the C# controller cod ...

AngularJS radio buttons can now be selected as multiple options

Currently, I am in the process of learning angular and have implemented a radio button feature in my program. However, I have encountered a perplexing issue that I cannot seem to explain. <!DOCTYPE html> <html> <head> <meta ch ...

Using await outside of an async function is not allowed

When working with a rest api in node.js, I have implemented functionality to automatically resize any uploaded images that are too large. However, I am encountering an error when trying to call my await method. Here is the code snippet: ': await is o ...

Analyzing the audio frequency of a song from an mp3 file with the help of HTML5 web audio API

Currently, I am utilizing the capabilities of the HTML5 web audio API to detect when a song's average sound frequency drops below a specific threshold and create corresponding markers. Although I have successfully implemented this using AudioNodes, th ...