C# 控制器和 HTML/JavaScript 视图 (MVC) 之间通信遇到问题

问题描述 投票:0回答:1

我在 MVC Web 应用程序中尝试向/从控制器和视图传递信息时遇到问题。也就是说,在我看来,我有两个文本字段,我想将信息传递给控制器中的方法,然后将相应的结果返回给 JavaScript,以便它可以对页面进行适当的更改。

//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在这里:

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

我不完全理解 AJAX 是否可以解决我的问题,如果可以,如何实际实现它。我也尝试过使用 [WebMethod],但我的解决方案不允许我引用 System.Web.Services (说它不存在)。我唯一的另一个想法是,我对 MVC 设置中的何处应该具有此功能有一个根本性的误解,因为理论上我可以将其包含在网页的 javascript 中。

javascript c# .net ajax
1个回答
0
投票

有几件事你需要担心,首先,你的控制器代码似乎不正确。

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

}

而且在你的ajax内容中你的URL也是错误的。因为它是一个 MVC 项目,你可以使用这样的东西

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);
            }
        });
© www.soinside.com 2019 - 2024. All rights reserved.