0

I'm new in MVC and trying to create a site for training.

I need to call a POST method in my controller through JavaScript.

This is my JavaScript method:

function ActivateAddStarAndRoleWithCategories(sender, args) {
    var discID = $('#DiscID').val();
    var starID = $('#StarID').val();
    var desc = $("#Description").val();

    var strID = "";

    $(':checkbox').each(function () {
        strID += this.checked ? this.id + "," : "";
    });

    strID = strID.substr(0, strID.length - 1);

    $.ajax({
        type: "POST",
        url: 'CreateCategoriesID',
        contentType: "application/json; charset=utf-8",
        data: {
            discID: discID,
            starID: starID,
            description: desc,
            catID: strID
        },
        dataType: "json",
        success: function () { alert("success!"); },
        error: function () { alert("Fail!"); }
    });
}

And this is my method in the controller:

[HttpPost]
public ActionResult CreateCategoriesID(string discID, string starID, string description, string catID)
{
    entities.AddStarAndRoleAndCategories(int.Parse(starID), description, int.Parse(discID), catID);

    return Json("OK", JsonRequestBehavior.AllowGet);
}

The view that activates the JavaScript function is already connected to the controller.

I always get error 500 - the server responded with a status of 500.

What am I doing wrong?

Thank you in advance!

Daniel A. White
  • 187,200
  • 47
  • 362
  • 445
itzick binder
  • 524
  • 10
  • 31
  • Add the `jquery` tag, since you're using it. EDIT: And the server is probably expecting `application/x-www-form-urlencoded; charset=UTF-8` in the `contentType` rather than a JSON. That's the usual type for HTML forms. – Alejandro Iván Feb 07 '16 at 20:15
  • In the debugger, what is the full url? – Ashish Musale Feb 07 '16 at 20:21
  • Try and start your MVC application in debug mode (http://stackoverflow.com/a/16916600/1134132) and make sure you are getting the input you expect. – sfs Feb 07 '16 at 20:38

1 Answers1

1

I would go with the examples from the jQuery docs.

Did you try something like...?

$.ajax({
    method: "POST",
    url: "CreateCategoriesID", // Insert your full URL here, that COULD be the problem too
    // This contentType is the default, so we can just ignore it
    //contentType: "application/x-www-form-urlencoded; charset=UTF-8",
    // I would also ignore the dataType unless your backend explicitly sends a JSON response header
    //dataType: "json",
    data: {
        discID: discID,
        starID: starID,
        description: desc,
        catID: strID
    }
}).done(function(msg) {
    alert('Success with message: ' + msg);
}).fail(function(jqXHR, textStatus) {
    alert('Failed with status: ' + textStatus);
});
Alejandro Iván
  • 3,969
  • 1
  • 21
  • 30