404 error calling an MVC controller action

There are two reasons I have seen this so far, and I have included both. I have creatively labeled them “Reason #1” and “Reason #2”. I leave it to you what will happen if I find a third reason.

Reason #1

I was using Ajax to call an MVC action like so:

        $.ajax({
            type: 'GET',
            url: '@Url.Content("~/Home/Stuff")',
            success: function (data) {
                $('#results').replaceWith(data);
            }, error: function (xhr) {
                alert(xhr.statusText);
            }
        });

And my Stuff action in the Home controller:

private ActionResult Stuff() {
            return PartialView("~/Views/Home/Stuff.cshtml");
}

But, I was deeply saddened to see that I was getting a “404 Not Found” error when I tried to do this. And it was because I made a simple mistake and hadn’t made my Stuff action public. Making that change fixed the issue:

public ActionResult Stuff() {
             return PartialView("~/Views/Home/Stuff.cshtml"); 
}

Reason #2

The second reason was that the URL was pointing to the wrong location. Shocker, I know. But here is the code that was causing the 404:

    $.ajax({
        url: '/Account/GetUsers',
        method: "GET",
    });

It appears that this would be fine – calling my controller Account, and the action GetUsers. However, this is ignoring that jQuery doesn’t know the complete path. The right code is:

    $.ajax({
        url: '@Url.Content("~/Account/GetUsers")',
        method: "GET",
    });

 

Advertisements

,

  1. 404 error calling an MVC controller action | Dinesh Ram Kali.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: