2017-01-09 21 views
0

我想在asp.net應用程序中註冊新用戶。我不想使用表單,而想使用Ajax。在沒有表格的asp.net應用程序中註冊新用戶

這是我的職務功能我的AccountController:

[System.Web.Mvc.HttpPost] 
public async Task<bool> Register(UserItem post) { 
    try { 
    var user = new ApplicationUser { UserName = post.UserName, Email = post.UserName }; 
    var result = await UserManager.CreateAsync(user, post.Password); 
    if (result.Succeeded) { 
     post.Id = user.Id; 
     await _userRepository.Save(post); 
     return true; 
    } 
    AddErrors(result); 
    } 
    catch (Exception e) { 
    Console.WriteLine(e); 
    } 
    // If we got this far, something failed, redisplay form 
    return false; 
} 

這是我的Ajax調用我的控制器:

var userJson = ko.toJSON(self.selectedUser); 
console.log(userJson); 
$.ajax({ 
    type: "POST", 
    url: "http://localhost:7061/Account/Register", 
    headers: "application/json; charset=UTF-8", 
    dataType: "json", 
    contentType: "application/json", 
    data: userJson, 
    error: function (xmlHttpRequest, textStatus, errorThrown, response) { 
    }, 
    success: function (response) { 
    console.log(response); 
    self.loadUsers(); 
    } 
}); 

但在我的控制寄存器功能不會被調用。

謝謝。

+0

你需要這個功能,AJAX的綁定功能的document.ready裏面。 –

+0

F12在您的瀏覽器上,並檢查「網絡」以查看您返回的結果。將幫助你找到錯誤。你有沒有試過數據:{post:userJson}, – KevDevMan

+0

爲什麼在'Task <>'中使用bool? –

回答

1

AccountController每個操作都需要返回一個ActionResult對象,或者在異步操作的情況下,需要返回Task<ActionResult>。否則,它不會被視爲一個操作,也不會將請求發送給它。

變化的方法來簽名:

public async Task<ActionResult> Register(UserItem post) { 

和,而不是返回truefalse,返回Json(true)Json(false)

相關問題