2

I've looked at a couple of threads now where they want to call a C# method from JavaScript in an ASP project. I can't figure out what I'm doing wrong. Here is my C# class:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Services;

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

        [HttpGet]
        public String GetCredentials()
        {
            return User.Identity.Name.ToString();
        }
    }
}

And here is the JavaScript I'm trying to call:

window.onload = function () {
    LiveSearch();
    getCredentials();
    //FetchAllUsers();
};

function getCredentials() {
    $.ajax({
        type: 'POST',
        url: '@Url.Action("GetCredentials", "Home")',
        dataType: 'json',
        cache: false,
        contentType: 'application/json; charset=utf­8',
        data: JSON.stringify(""),
        success: function (cred) {
            alert(cred);
        },
        error: function (error) {
            alert(JSON.stringify(error));
        }
    });
}

I keep getting a 404 Not Found status back. It's an ASP site that's deployed on an IIS, on one of my workplaces servers. We are using Windows Authentication, so I'd like to get the credentials of whoever is logged in and store it for something else later.

I'm kind of at my wits end here. Anyone got any ideas?

5
  • 4
    Easy, you have declared [HttpGet] on your action method, while you POST to it from jQuery... Commented Apr 11, 2017 at 13:31
  • @kayess I'm no JS wiz, but some of the answers I looked at said that was the answer to the problem. Switching to "Get" doesn't fix this. Commented Apr 11, 2017 at 13:32
  • did you tried just "/Home/GetCredentials" as url? also like mentioned change to GET remove the contentType and change dataType to "text" as your controller is not returning json Commented Apr 11, 2017 at 13:33
  • 1
    @kayess Comment is the solution. Simply change [HttpGet] to [HttpPost]. Commented Apr 11, 2017 at 13:34
  • @Kris That seemed to do the trick for a get request at least. Thanks dude. Make it an answer an I'll accept it :) Commented Apr 11, 2017 at 13:43

1 Answer 1

2

Have you just tried to reach "/Home/GetCredentials" as URL? Also like mentioned, change to GET method, remove the contentType and change dataType to "text" as your controller is not returning JSON.

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

1 Comment

Actually I tried his solution, which didn't do anything.

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.