MVC项目中C#控制器与HTML/JavaScript视图通信故障求助
MVC控制器与视图信息传递问题解决方案
问题背景
在MVC Web应用开发中,需要将视图中两个文本框的内容传递给控制器的GetInfo方法,再将处理结果返回给JavaScript实现页面无刷新更新。当前AJAX调用无效,尝试[WebMethod]时无法引用System.Web.Services,同时疑惑方法在MVC架构中的位置是否正确。
一、修正控制器方法
ASP.NET Core MVC中无需使用[WebMethod],需通过[HttpPost]标记动作方法,同时优化异步逻辑避免阻塞。以下是修正后的控制器代码:
using LiquipediaScraper.Models; using Microsoft.AspNetCore.Mvc; using System; using System.Collections.Generic; using System.Net.Http; using System.Threading.Tasks; using HtmlAgilityPack; using System.Text.Json; namespace LiquipediaScraper.Controllers { public class HomeController : Controller { [HttpPost] public async Task<IActionResult> GetInfo(string teamName) { if (string.IsNullOrEmpty(teamName)) { return BadRequest("战队名称不能为空"); } // 补充完整URL协议前缀,避免HttpClient请求失败 string teamUrl = $"https://liquipedia.net/overwatch/{teamName}"; var response = await CallUrl(teamUrl); if (response != null) { List<List<string>> players = ParseHtmlForPlayers(response); List<Player> playerList = new List<Player>(); for (int i = 0; i < players[0].Count; i++) { playerList.Add(new Player { Tag = players[0][i], Role = players[1][i] }); } // 直接返回JsonResult,框架自动处理序列化 return Json(playerList); } else { return NotFound("未获取到战队信息"); } } // 异步请求网页内容 private async Task<string> CallUrl(string url) { using var client = new HttpClient(); var httpResponse = await client.GetAsync(url); return httpResponse.IsSuccessStatusCode ? await httpResponse.Content.ReadAsStringAsync() : null; } // HTML解析方法 private List<List<string>> ParseHtmlForPlayers(string html) { // 保留原解析逻辑 return new List<List<string>>(); } } }
二、修正AJAX调用
AJAX是实现无刷新交互的正确方案,问题出在URL路径错误和数据传递格式不当。修正后的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>`); $.ajax({ type: "POST", // MVC路由格式:/控制器名/动作方法名 url: "/Home/GetInfo", // 传递键值对,确保与控制器方法参数名一致 data: { teamName: team1 }, dataType: "json", success: function (playerList) { // 动态生成队员信息HTML并更新页面 let resultHtml = `<h3>${team1} 队员信息</h3><ul>`; playerList.forEach(player => { resultHtml += `<li>ID: ${player.Tag} | 位置: ${player.Role}</li>`; }); resultHtml += "</ul>"; $("#divResult").html(resultHtml); }, error: function (xhr) { $("#divResult").html(`请求失败:${xhr.responseText}`); } }); });
三、关键问题说明
- AJAX的合理性:AJAX是MVC前后端无刷新交互的标准方案,完全适配当前需求。
- [WebMethod]的替代方案:ASP.NET Core MVC已弃用WebForms的
[WebMethod],改用[HttpPost]/[HttpGet]标记动作方法,配合JsonResult返回数据即可。 - 方法位置规范:
GetInfo涉及后端网页爬取与数据解析,属于服务器端业务逻辑,放在控制器是正确的;绝不能放到前端JS中,否则会暴露敏感逻辑且无法实现跨域爬取。
内容的提问来源于stack exchange,提问作者Clion is the bane of my life
相关产品推荐
相关产品推荐

