簡體   English   中英

asp.net mvc ajax發布返回404找不到

[英]asp.net mvc ajax post returns 404 not found

我正在嘗試使用jquery ajax函數執行ajax請求。 我的行為很奇怪。 我的文件夾結構如下:

文件夾結構

我的客戶端ajax調用(在UserManagement / Index.cshtml中)如下所示:

var rolename = viewModel.roleName();
$.ajax({
     type: "POST",
     url: '@Url.Action("AddRole", "UserManagement")',
     contentType: "application/json; charset=utf-8",
     data: { rolename: rolename },
     success: function(data) {
         var role = new Role(rolename);
         model.addRole(role);
         model.appendItem("#accordion", role.getItem());
         viewModel.roleName("");            
     }
});

在我的UserManagementController.cs中,我執行以下操作:

    // GET: /UserManagement/
    public ActionResult Index()
    {
        var serializer = new JavaScriptSerializer();
        var context = new ApplicationDbContext();
        var users = context.Users.ToList();
        var roles = context.Roles.ToList();


        ViewBag.Users = users;
        ViewBag.Roles = roles;
        return View();
    }

    //
    // POST: /UserManagement/AddRole
    [HttpPost]
    public string AddRole(string rolename)
    {

        Response.StatusCode = 200;
        return "gsfgdg";
    }

我已經嘗試使用GET而不是POST或將AddRole更改為void類型以及其他任何內容,但是我無法使其正常工作。 我總是收到“找不到404”。 有人可以幫忙嗎?

提前致謝!

如果刪除Content-Type,您的案例將起作用。

Case 1: If we use Content-Type: "application/json"

當您請求Content / Type的application / json時,在服務器端ScriptServices期望數據為JSON序列化字符串。

但是,我們可以看到"Invalid JSON primitive ***"通常是響應的結果。

在這里,我們應該理解將jQuery的“數據”選項傳遞為“ {'param':'value'}”,而不是{'param':'value'}。

因此,就您而言,要實現解決方案:我們需要提供以下data

var rolename = viewModel.roleName();
$.ajax({
     type: "POST",
     url: '@Url.Action("AddRole", "UserManagement")',
     contentType: "application/json; charset=utf-8",
     data: "{ 'rolename':'" + rolename +"' }",
     success: function(data) {
         var role = new Role(rolename);
         model.addRole(role);
         model.appendItem("#accordion", role.getItem());
         viewModel.roleName("");            
     }
});

Case 2: If we skip Content-Type: "application/json"

我們應該提供jQuery的“數據”選項作為JSON對象{'param':'value'}或{param:'value'}。 (與您一樣)

希望能幫助到你 :)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM