简体   繁体   English

对Controller中的JsonResult进行Ajax调用失败,并显示404错误,“未找到资源”

[英]Ajax call to JsonResult in Controller fails with 404 error, “resource not found”

Here is my ajax code in my "ManageUserRoles.cshtml": 这是我的“ ManageUserRoles.cshtml”中的ajax代码:

//HIT THE DATABASE FOR USERNAME GIVING IT THIS USERNAME
function isUserValid(thisUser) {


    $.ajax({
        url: "/Roles/isUserValid/" + thisUser,
        type: 'POST',
        success: handleResultResponseUserName,
        error: function (xhr) { alert("Error..."); }
    });
}


//handles data back from ajax call
//RESET INPUT IF NO USER IF FOUND IN USER'S TABLE
function handleResultResponseUserName(ResponseObject) {

    if (ResponseObject == "no user with this number") {

        $('#frmGetRoles').find('input[name="UserName"]').val(null);

    }
    else {

        //DO NOTHING

    }

}

Here is my JsonResult in my RolesController: 这是我的RolesController中的JsonResult:

[HttpPost]
[ValidateAntiForgeryToken]
public JsonResult isUserValid(string username)
{
    var name = string.Empty;

    var CheckUserExists = (from c in _db.AspNetUsers
                       where (c.UserName.Equals(username))
                       select c);


    var results = new JsonResult();

    if (CheckUserExists.Any())
    {

        name = CheckUserExists.First().UserName;

    }

    else
    {
        name = "no user with this name in database";

    }
    return Json(name, JsonRequestBehavior.DenyGet); 
}

I've got almost exact code working in a different application and I cut and pasted into a new one where I am trying to use it for Roles management. 我在几乎不同的应用程序中都能使用几乎完全相同的代码,并且将其剪切并粘贴到一个新的应用程序中,以尝试将其用于角色管理。

The json reference is there, and in web.config. json引用在那里,在web.config中。 But when I put a breakpoint inside the JsonResult, it never stops there and an error is returned from the client javascript (404 resource not found). 但是,当我在JsonResult中放置一个断点时,它永远不会停在那里,并且会从客户端javascript返回错误(找不到404资源)。 There is no other json stuff being used in this new app . 此新应用程序中没有使用其他json东西。 . .yet. 。然而。

I can hit f5 and it returns: http://localhost/StoreMasterSecure/Roles/ManageUserRoles which is the view that has the button that runs the ajax. 我可以按f5键,它返回: http:// localhost / StoreMasterSecure / Roles / ManageUserRoles ,它是具有运行ajax的按钮的视图。 It all gets to the ajax call and then nothing happens and Chrome Developer Tools console shows 404 error. 一切都转到了ajax调用,然后什么也没有发生,Chrome开发者工具控制台显示404错误。

Even if I type in the URL the path, I get the resource not found 404 page: http://localhost/StoreMaster/Roles/isValidUser/xxxx@xxx.com 即使我在URL中输入路径,也无法找到404页面: http://localhost/StoreMaster/Roles/isValidUser/xxxx@xxx.com

(isValidUser is the JsonResult in the controller, in same controller that ManageUserRoles ActionResult exists and works) (isValidUser是控制器中的JsonResult,与存在ManageUserRoles ActionResult并起作用的控制器相同)

To ensure you url's are correctly generated, use the Url.Action() method and pass the data using the ajax data option. 为了确保正确生成url,请使用Url.Action()方法,并使用ajax data选项传递data Change your ajax to 将您的ajax更改为

$.ajax({
    url: '@Url.Action("isUserValid", "Roles")', // change this
    data: { username: thisUser }, // add this
    type: 'POST',
    success: handleResultResponseUserName,
    error: function (xhr) { alert("Error..."); }
});

You also need to remove the [ValidateAntiForgeryToken] attibute from your controller method since you not passing the token. 您还需要从控制器方法中删除[ValidateAntiForgeryToken]属性,因为您没有传递令牌。

Side note: MVC comes with a RemoteAttribute to handle this scenario. 旁注:MVC带有RemoteAttribute来处理这种情况。 Refer How to: Implement Remote Validation in ASP.NET MVC which means you do not need your script. 请参阅如何:在ASP.NET MVC中实现远程验证,这意味着您不需要脚本。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM