1

I am trying to submit an ajax request from an external JavaScript file in ASP.NET MVC. I'm getting a 500. What am I doing wrong?

Ajax call (From external JS file)

$.ajax({
    type: "POST",
    url: '/Home/AjaxEndpoint',
    data: { jsonData: "testing" },
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: successFunc,
    error: errorFunc
});

Controller Action Method (That should be catching the request)

public class HomeController : Controller
{
    // GET: Home
    public ActionResult Index()
    {
        return View();
    }

    [HttpGet]
    public void AjaxEndpoint()
    {
        var thing = 1 + 2;
    }

    // AJAX endpoint for GetProducts.js
    [HttpPost]
    public void AjaxEndpoint(string jsonData)
    {
        var thing = 1 + 2;
    }

}

Error I'm getting enter image description here

3
  • 1
    You need to put your code in the question, not images of it. And remove the contentType option (your not stringifying the data) Commented Apr 10, 2016 at 2:42
  • Please do not edit the question with the answer (I have removed it). Add your own answer and accept it to close this out. Commented Apr 10, 2016 at 8:36
  • If you have a proposed solution, such as "remove the contentType option", please create an answer so that I can accept it rather than burying it in the comments of the question. Commented Apr 18, 2016 at 21:23

2 Answers 2

2

You either need to remove the contentType option

$.ajax({
    type: "POST",
    url: '/Home/AjaxEndpoint',
    data: { jsonData: "testing" },
    dataType: "json",
    success: successFunc,
    error: errorFunc
});

or alternatively, stringify the data

$.ajax({
    type: "POST",
    url: '/Home/AjaxEndpoint',
    data: JSON.stringify({ jsonData: "testing" }),// modify
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: successFunc,
    error: errorFunc
});
Sign up to request clarification or add additional context in comments.

Comments

0

Your ajax call needs to be to an ActionResult in the controller, The controller performs and returns the data to the page

 [HttpPost]
    public ActionResult ajaxcall(string ids)
    {
        String Data = code to perform
        return Json(Data);
    }

this is the basic idea. Javascript makes the call and uses the json data returned on the clients page

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.