ASP.NET Core AJAX无法正常工作?

时间:2016-08-23 08:42:46

标签: ajax asp.net-core

我正在尝试在ASP.NET Core中实现AJAX,因此我使用"个人用户帐户"创建了一个新的默认" ASP.NET核心Web应用程序(.NET Core)。

我添加了" Microsoft.jQuery.Unobtrusive.Ajax":" 3.2.3"在project.json下"依赖"部分。

for" Register.cshtml"我已将声明更改为

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

at&#34; Register&#34;在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。

感谢Advanced提供任何帮助, AG

1 个答案:

答案 0 :(得分:2)

我添加了“jquery-ajax-unobtrusive”:“3.2.4”通过bower.json,然后引用了jquery.unobtrusive-ajax.js,现在它正在工作。 感谢@jerome的帮助