JavaScript POST 在连接到 MVC 控制器时下降

JavaScript POST falls when connect to MVC controller

本文关键字:控制器 MVC POST 连接 JavaScript      更新时间:2023-09-26

我是MVC的新手,正在尝试创建一个培训网站。

我需要通过JavaScript在我的控制器中调用一个POST方法。

这是我的JavaScript方法:

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!"); }
    });
}

这是我在控制器中的方法:

[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);
}

激活 JavaScript 函数的视图已连接到控制器。

我总是收到错误 500 - 服务器以 500 的状态响应。

我做错了什么?

提前谢谢你!

我会使用jQuery文档中的示例。

你有没有尝试过类似的东西...?

$.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);
});