3

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

Structure of files][1

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.

7
  • 2
    You need to decorate the GetAllPeople action with [HttpPost], otherwise it will only respond to GET requests Commented May 4, 2017 at 1:25
  • 2
    Drop the word "Controller" in the helpers @Url.Action("GetAllPeople", "Home") 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. Commented May 4, 2017 at 1:29
  • Thanks, I'll give that a go! 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. Commented May 4, 2017 at 1:37

3 Answers 3

3

Here's a working demo: https://dotnetfiddle.net/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 comments, the action returns this:

return Json(people);

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

Sign up to request clarification or add additional context in comments.

4 Comments

Still having problems with mine, but I'll take a look at the example, thanks.
The view you shared in the code... is that Index.cshtml?
yep, it is. it's the startup page
thanks, that's got it! it was a mix of needing the write call, making sure the table to add into matched the class name and making sure the field names were correct.
2

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'.

Comments

0

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 compiled 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.com/watch?v=we1_aL1KYiE

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.