Asp.Net中如何用Ajax调用ActionResult?求助无刷新加载新题目
Hey there! Let's work through why your Ajax call to load a new question (when clicking "2") isn't working. I'll break down common issues and fixes starting with the frontend (since you didn't share that code, it's often the main culprit) then move to the backend bits you provided.
1. Fix the Frontend Ajax Implementation
Your action uses [HttpPost], so your Ajax request must use POST and send the id parameter correctly. Here's a working jQuery example (adjust for vanilla JS if needed):
// Assume your "2" element is a button with id="btnLoadQuestion" $("#btnLoadQuestion").click(function(e) { e.preventDefault(); // Stop default button behavior (like form submission) const questionId = 2; // Or grab this dynamically if the ID changes $.ajax({ url: '/YourControllerName/BaiTestIQ', // Replace with your actual controller name! type: 'POST', data: { id: questionId }, // Matches the action's parameter name "id" dataType: 'html', // Use 'json' if you return JSON instead of HTML success: function(response) { // Swap out the old question with the new content $("#questionContainer").html(response); console.log("New question loaded successfully!"); }, error: function(xhr, status, error) { // Critical for debugging—check what went wrong console.log("Error loading question: " + error); console.log("Status code: " + status); console.log("Server response: " + xhr.responseText); } }); });
Key checks for your frontend:
- Replace
/YourControllerName/BaiTestIQwith your actual controller (e.g., if your controller isIQTestController, use/IQTest/BaiTestIQ). - Ensure the
dataobject's key (id) exactly matches your action's parameter name. - Match
dataTypeto what your action returns:htmlfor a partial view,jsonfor JSON data. - Always include the
errorhandler—it’s the fastest way to spot issues like 404s or 500s.
2. Verify Your Backend Action
Looking at your code snippet, here are a few critical fixes:
a. Return the Right Result Type
Your action needs to send content the frontend can render. For HTML, return a PartialView:
[HttpPost] public ActionResult BaiTestIQ(int id) { var cauhoi = from q in data.Questions join a in data.Answers on q.MaTests equals "IQ" where q.MaCHoi == a.MaCHoi && a.keys == id select new baitest() { Cauhoi = q.Noidung, DAn1 = a.DAn1, DAn2 = a.DAn2, DAn3 = a.DAn3, DAn4 = a.DAn4, DAn5 = a.DAn5, DAn6 = a.DAn6, }; // Make sure your query returns data var question = cauhoi.FirstOrDefault(); if (question == null) { return Content("No question found for this ID."); } // Return a partial view with the question model return PartialView("_QuestionPartial", question); }
If you prefer JSON (to render with JavaScript), replace the last line with:
return Json(question); // In newer MVC versions, no need for JsonRequestBehavior.AllowGet for POST
b. Validate Your Query Logic
Test your LINQ query with a known id to ensure it returns data. If cauhoi is empty, your filters might be too strict (e.g., q.MaTests == "IQ" might not match any records, or a.keys == id is excluding all results).
c. Confirm Route Matching
The default MVC route ({controller}/{action}/{id}) works for POST requests as long as your controller and action names are correct. Double-check you’re using the right names in your Ajax URL.
3. Debugging Tips
- Open your browser’s Developer Tools (F12), go to the Network tab, then click the "2" button:
- If no request appears: Your click event isn’t bound properly (use
$(document).on('click', '#btnLoadQuestion', function() {...})if the element loads dynamically). - 404 error: Your Ajax URL is wrong (double-check controller/action names).
- 400 error: The
idparameter isn’t being sent correctly, or model binding failed. - 500 error: There’s an exception in your action—check the server logs or response text for details.
- If no request appears: Your click event isn’t bound properly (use
- Add debug breakpoints or
Console.WriteLinein your action to confirm it’s being hit and whatidvalue it receives.
Give these steps a shot, and let me know if you hit specific errors or need more help!
内容的提问来源于stack exchange,提问作者Cuong Truong Quoc

