2015-11-01 68 views
0

這裏是我的 「ManageUserRoles.cshtml」 我的Ajax代碼:Ajax調用JsonResult在控制器出現故障404錯誤, 「資源未找到」

//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 

    } 

} 

這是我在我的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); 
} 

我已經在不同的應用程序中使用了幾乎完全相同的代碼,並且我剪切並粘貼到了一個新的代碼中,我嘗試將其用於角色管理。

json引用在那裏,並在web.config中。但是當我在JsonResult中放置一個斷點時,它永遠不會停止,並且從客戶端javascript(404資源未找到)返回錯誤。在這個新應用程序中沒有其他json的東西被使用。 。 。然而。

我打F5和它返回: http://localhost/StoreMasterSecure/Roles/ManageUserRoles 這是具有運行ajax的按鈕的視圖。這一切都得到ajax調用,然後什麼也沒有發生,Chrome開發者工具控制檯顯示404錯誤。

即使我在URL中鍵入路徑,我得到的資源找不到404頁: http://localhost/StoreMaster/Roles/isValidUser/[email protected]

(isValidUser是JsonResult控制器,在ManageUserRoles的ActionResult存在相同的控制器和作品)

+0

你的方法裝飾有'[ValidateAntiForgeryToken]',但你永遠不會傳遞該標記(要麼傳遞它,要麼刪除該屬性),但爲什麼不使用'[Remote]'屬性?和輸入網址不會工作,因爲你的方法是一個POST,而不是一個GET。 –

+0

Stephen,我把[ValidateAntiForgeryToken]放在那裏,因爲我看到它高於所有其他ActionResults。它不適用於它或沒有它。我把它拿走了,試圖把[Remote]加下劃線並加上紅色,解釋如下:「由於其保護級別,RemoteAttribute()無法訪問。」然而,我並不需要這個在我的工作應用程序,它也使用POST方法和工作。表單字段數據到達.ajax調用。但是我找不到404資源。 – JustJohn

+0

(1)您不理解「RemoteAttribute」是什麼 - 將其應用於您的財產。請參閱[如何:在ASP.NET MVC中實現遠程驗證](https://msdn.microsoft.com/zh-cn/library/gg508808(VS.98).aspx)。 (2)如果你沒有傳遞令牌,你必須移除'[ValidateAntiForgeryToken]'。 (3)你的ajax選項需要是'url:'@ Url.Action(「isUserValid」,「Roles」)'和'data:{username:thisUser},' –

回答

0

爲確保正確生成網址,請使用Url.Action()方法並使用ajax data選項傳遞數據。你的Ajax更改爲

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

你也需要,因爲你沒有通過令牌從您的控制器的方法去除[ValidateAntiForgeryToken] attibute。

備註:MVC附帶RemoteAttribute來處理這種情況。這意味着你不需要你的腳本,請參考How to: Implement Remote Validation in ASP.NET MVC

+0

謝謝Stephen。將學習RemoteAttribute。 – JustJohn

+0

我的意思是遠程驗證。不確定,但是你的鏈接解釋瞭如何在MVC 3中做到這一點。我現在在MVC 5中,MS的團隊每小時進行一百萬英里。 – JustJohn

+0

沒有區別 - 完全相同的代碼適用:) –

相關問題