ASP.NET AJAX无法找到控制器,请求技术解决方案
Hey there, I see you’ve spent 3 hours troubleshooting this AJAX-to-controller issue—let’s break this down and fix it step by step!
项目背景 & 现有代码
First, here's your project structure for reference:
HomeController.cs Code
(Quick heads-up: Your code has a duplicate public class HomeController : Controller line—be sure to remove that extra declaration to avoid compilation errors!)
public class HomeController : Controller { [WebMethod] public static int OnSubmit() { return 1; } [HttpGet] public ActionResult Index() { return View("Index"); } }
Index.cshtml AJAX Script (Partial)
<script type="text/javascript"> function sendRequest() { // Your incomplete AJAX logic here } </script>
Core Issues Blocking Your AJAX Call
The main problems here stem from mixing WebForms and MVC patterns—they don’t play nice together:
[WebMethod]is a WebForms-specific attribute; it won’t work in an MVC Controller. MVC uses action methods with HTTP verb attributes (like[HttpPost]) instead.- Static methods can’t be used as MVC action methods by default—MVC relies on controller instances to handle requests.
- You haven’t specified an HTTP verb for your
OnSubmitmethod, and AJAX calls typically use POST (not GET) for form/submit actions.
Fixed Solution
Updated HomeController.cs
Replace the WebForms-style code with proper MVC conventions:
public class HomeController : Controller { // Replace [WebMethod] with MVC's [HttpPost], remove static modifier [HttpPost] public ActionResult OnSubmit() { // Return JSON for clean AJAX handling (more flexible than raw int) return Json(1); // If you strictly need a plain integer response, use: // return Content("1", "text/plain"); } [HttpGet] public ActionResult Index() { return View("Index"); } }
Complete Working AJAX Script (jQuery Example)
Assuming you’re using jQuery (the most common AJAX library for MVC), here’s a full, tested sendRequest function:
<script src="~/Scripts/jquery-3.7.1.min.js"></script> <!-- Make sure jQuery is loaded first! --> <script type="text/javascript"> function sendRequest() { $.ajax({ url: '@Url.Action("OnSubmit", "Home")', // Use MVC's URL helper to avoid hardcoding paths type: 'POST', contentType: 'application/json; charset=utf-8', success: function(response) { console.log("Success! Response:", response); // Add your post-success logic here (e.g., alert("Returned: " + response)) }, error: function(xhr, status, error) { console.error("Request failed:", error); // Handle errors here (e.g., alert("Something went wrong!")) } }); } </script>
Extra Tips
- Always use
@Url.Actionto generate controller/action URLs—this avoids broken links when deploying to different environments. - If you need to pass data to the controller, add parameters to the
OnSubmitmethod and include adataproperty in your AJAX call (e.g.,data: JSON.stringify({username: "Zeal"})). - Double-check that jQuery is loaded before your AJAX script—missing jQuery is a super common gotcha!
内容的提问来源于stack exchange,提问作者ZeáL
相关产品推荐
相关产品推荐

