2016-08-23 101 views
1

我想在ASP.NET Core中实现AJAX,所以我创建了一个新的默认“ASP.NET核心Web应用程序(.NET核心)与”个人用户帐户“。 Unobtrusive.Ajax“: ” “第ASP.NET核心AJAX不工作?

为 ”3.2.3“ 的下project.json” 依赖Register.cshtml“ 我已经改变了声明

<form asp-controller="Account" asp-action="Register" asp-route-returnurl="@ViewData["ReturnUrl"]" data-ajax="true" data-ajax-method="POST" class="form-horizontal"> 

在 ”中的AccountController注册“ 行动我已经改变它来检查帖子是否使用AJAX。

[HttpPost] 
    [AllowAnonymous] 
    [ValidateAntiForgeryToken] 
    public async Task<IActionResult> Register(RegisterViewModel model, string returnUrl = null) 
    { 
     var isAjax = HttpContext.Request.Headers["X-Requested-With"] == "XMLHttpRequest"; 

     ViewData["ReturnUrl"] = returnUrl; 
     if (ModelState.IsValid) 
     { 
      var user = new ApplicationUser { UserName = model.Email, Email = model.Email }; 
      var result = await _userManager.CreateAsync(user, model.Password); 
      if (result.Succeeded) 
      { 
       // For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=532713 
       // Send an email with this link 
       //var code = await _userManager.GenerateEmailConfirmationTokenAsync(user); 
       //var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: HttpContext.Request.Scheme); 
       //await _emailSender.SendEmailAsync(model.Email, "Confirm your account", 
       // $"Please confirm your account by clicking this link: <a href='{callbackUrl}'>link</a>"); 
       await _signInManager.SignInAsync(user, isPersistent: false); 
       _logger.LogInformation(3, "User created a new account with password."); 
       return RedirectToLocal(returnUrl); 
      } 
      AddErrors(result); 
     } 

     // If we got this far, something failed, redisplay form 
     return View(model); 
    } 

问题是isAjax总是返回false。

在先进的感谢您的帮助, AG

+1

在想知道为什么isAjax总是错误的,你应该首先检查你的请求是否确实有头文件“X-Requested-With”。我相信你不会 –

+1

在你的project.json中添加Microsoft.jQuery.Unobtrusive.Ajax只是在你的项目中添加了对这个包的引用,但并不意味着你正在使用它。你应该学会如何正确地使用这个库。否则,如果你真的想在AJAX中发送你的HTTP请求(我不明白其中的原因),尝试纯JavaScript或使用jQuery(与Unobtrusive.Ajax不同) –

回答

2

我已经加入“jQuery的Ajax的不显眼”:“3.2.4”直通bower.json再参考jquery.unobtrusive,ajax.js和现在它正在工作。 谢谢@jerome的帮助