最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - AJAX 404 Error - Call to controller action .Net MVC - Stack Overflow

programmeradmin1浏览0评论

I have a fairly simply .NET application with one page.

The code is meant to populate a table when run by calling the relevant controller to get the code and printing it out using a script.

My controller:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using techTest3.Models;  

namespace techTest3.Controllers
{
    public class HomeController : Controller
    {
    public ActionResult Index()
    {
        return View();
    }

    public JsonResult GetAllPeople()
    {
        TechTestEntities testTechObj = new TechTestEntities();
        var people = testTechObj.People.Select(x => new
        {
            Id = x.PersonId,
            Name = x.FirstName,
            Surname = x.LastName,
            Valid = x.Var1,
            Authorised = x.Var2
        }).ToList();
        return Json(people, JsonRequestBehavior.AllowGet);
    }  

}
}

My view:

@{
ViewBag.Title = " Showing Data Using jQuery Ajax Call JSON in ASP.NET MVC";
} 
<h1>Showing Data Using jQuery Ajax Call JSON in ASP.NET MVC </h1> 

<div>
    <table id = "tblEmployee" class = "tblEmployee" >
    <thead>
    <!---<img src = "~/Loading.gif" alt = "Loading" id = "imgLoading" class = "Load" />-->
    </thead> 

        <tbody>
         </tbody> 
        </table> 
        </div> 

    <script src="~/Scripts/jquery-1.10.2.min.js"></script>
    <script type = "text/javascript" >
    $(document).ready(function()
    {
        $("#tblEmployeetbodytr").remove();
        $.ajax
        ({
            type: 'POST',
            url: '@Url.Action("GetAllPeople")',
            dataType: 'json',
            data: {},
            success: function(data)
            {
            $("#imgLoading").hide();
            var items = '';
            var rows = "<tr>" +  
                    "<th align='left' class='EmployeeTableTH'>Employee ID</th><th align='left' class='EmployeeTableTH'>Name</th><th align='left' class='EmployeeTableTH'>Project Name</th><th align='left' class='EmployeeTableTH'>Manager Name</th><th align='left' class='EmployeeTableTH'>City</th>" +  
                    "</tr>";  
            $('#tblEmployeetbody'

).append(rows);

        $.each(data, function(i, item)  
        {  
            var rows = "<tr>" +  
                "<td class='EmployeeTableTD'>" + item.Id + "</td>" +  
                "<td class='EmployeeTableTD'>" + item.FirstName + "</td>" +  
                "<td class='EmployeeTableTD'>" + item.LastName + "</td>" +  
                "<td class='EmployeeTableTD'>" + item.Var1 + "</td>" +  
                "<td class='EmployeeTableTD'>" + item.Var2 + "</td>" +  
                "</tr>";  
            $('#tblEmployeetbody').append(rows);  
        });  
        },
        error: function(ex)
        {
        var r = jQuery.parseJSON(response.responseText);
        alert("Message: " + r.Message);
        }
        });
        return false;
        }); </script> 
        <style type = "text/css" >
        </style> 

Where TechTestEntities is the name of an edmx model that references a SQL database.

When I debug the application, I get a 404 not found error. This happens with url: '<%= Url.Action("GetAllPeople", "HomeController") %>', and url: '/Controllers/HomeController/GetAllPeople', and also url: '@Url.Action("/HomeController.cs/GetAllPeople").

Is there something obvious I'm missing? Please bear in mind I'm very new to AJAX and Javascript when answering.

I have a fairly simply .NET application with one page.

The code is meant to populate a table when run by calling the relevant controller to get the code and printing it out using a script.

My controller:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using techTest3.Models;  

namespace techTest3.Controllers
{
    public class HomeController : Controller
    {
    public ActionResult Index()
    {
        return View();
    }

    public JsonResult GetAllPeople()
    {
        TechTestEntities testTechObj = new TechTestEntities();
        var people = testTechObj.People.Select(x => new
        {
            Id = x.PersonId,
            Name = x.FirstName,
            Surname = x.LastName,
            Valid = x.Var1,
            Authorised = x.Var2
        }).ToList();
        return Json(people, JsonRequestBehavior.AllowGet);
    }  

}
}

My view:

@{
ViewBag.Title = " Showing Data Using jQuery Ajax Call JSON in ASP.NET MVC";
} 
<h1>Showing Data Using jQuery Ajax Call JSON in ASP.NET MVC </h1> 

<div>
    <table id = "tblEmployee" class = "tblEmployee" >
    <thead>
    <!---<img src = "~/Loading.gif" alt = "Loading" id = "imgLoading" class = "Load" />-->
    </thead> 

        <tbody>
         </tbody> 
        </table> 
        </div> 

    <script src="~/Scripts/jquery-1.10.2.min.js"></script>
    <script type = "text/javascript" >
    $(document).ready(function()
    {
        $("#tblEmployeetbodytr").remove();
        $.ajax
        ({
            type: 'POST',
            url: '@Url.Action("GetAllPeople")',
            dataType: 'json',
            data: {},
            success: function(data)
            {
            $("#imgLoading").hide();
            var items = '';
            var rows = "<tr>" +  
                    "<th align='left' class='EmployeeTableTH'>Employee ID</th><th align='left' class='EmployeeTableTH'>Name</th><th align='left' class='EmployeeTableTH'>Project Name</th><th align='left' class='EmployeeTableTH'>Manager Name</th><th align='left' class='EmployeeTableTH'>City</th>" +  
                    "</tr>";  
            $('#tblEmployeetbody'

).append(rows);

        $.each(data, function(i, item)  
        {  
            var rows = "<tr>" +  
                "<td class='EmployeeTableTD'>" + item.Id + "</td>" +  
                "<td class='EmployeeTableTD'>" + item.FirstName + "</td>" +  
                "<td class='EmployeeTableTD'>" + item.LastName + "</td>" +  
                "<td class='EmployeeTableTD'>" + item.Var1 + "</td>" +  
                "<td class='EmployeeTableTD'>" + item.Var2 + "</td>" +  
                "</tr>";  
            $('#tblEmployeetbody').append(rows);  
        });  
        },
        error: function(ex)
        {
        var r = jQuery.parseJSON(response.responseText);
        alert("Message: " + r.Message);
        }
        });
        return false;
        }); </script> 
        <style type = "text/css" >
        </style> 

Where TechTestEntities is the name of an edmx model that references a SQL database.

When I debug the application, I get a 404 not found error. This happens with url: '<%= Url.Action("GetAllPeople", "HomeController") %>', and url: '/Controllers/HomeController/GetAllPeople', and also url: '@Url.Action("/HomeController.cs/GetAllPeople").

Is there something obvious I'm missing? Please bear in mind I'm very new to AJAX and Javascript when answering.

Share Improve this question edited May 4, 2017 at 1:23 Grant Winney 66.5k13 gold badges120 silver badges167 bronze badges asked May 4, 2017 at 1:20 peanutpeanut 2834 silver badges12 bronze badges 7
  • 2 You need to decorate the GetAllPeople action with [HttpPost], otherwise it will only respond to GET requests – Maria Ines Parnisari Commented May 4, 2017 at 1:25
  • 2 Drop the word "Controller" in the helpers @Url.Action("GetAllPeople", "Home") – Jasen Commented May 4, 2017 at 1:25
  • 1 Additionally since JSON controller marked as HttpPost returning JsonResult, remove JsonRequestBehavior.AllowGet and return Json(people) instead. – Tetsuya Yamamoto Commented May 4, 2017 at 1:29
  • Thanks, I'll give that a go! – peanut Commented May 4, 2017 at 1:29
  • Still getting 404 errors after trying all suggestions - debug goes to /Home/index, and neither "GetAllPeople", "Home" or "GetAllPeople, HomeController" works. – peanut Commented May 4, 2017 at 1:37
 |  Show 2 more ments

3 Answers 3

Reset to default 3

Here's a working demo: https://dotnetfiddle/kE5Px7

I just made one change, added the HttpPost attribute to the action you're calling.

[HttpPost]
public JsonResult GetAllPeople()

and as suggested in the ments, the action returns this:

return Json(people);

The URL of the AJAX call remains the same: url: '@Url.Action("GetAllPeople")'.

Only one change you need to do is, change HomeController to Home. We use only Controller name in call. For example '/Home/GetAllPeople' . This is wrong to write '/Controllers/HomeController/GetAllPeople'.

I found this post based on the problem, but the solutions did not work. For me, the AJAX call would NOT find the controller. The call previously worked and one day it just stopped working. I modified the controller to add new methods and renamed the AJAX call and still nothing.
The ONLY solution that actually worked for me was to create a new controller, copy all of the methods over and rename the AJAX call. Somethin went awry in visual studio and the piled version, but I do not know what. I just wanted to post this situation in case it helps someone avoid the hours it took me to debug this issue.
Happy Coding!

The referenced video is exactly what was happening to me: https://www.youtube./watch?v=we1_aL1KYiE

发布评论

评论列表(0)

  1. 暂无评论