如何对控制器动作进行Ajax调用 [英] How to make an ajax call to controller action

查看:49
本文介绍了如何对控制器动作进行Ajax调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我第一次打Ajax电话,我真的很困惑.

我正在使用ASP.NET MVC,Identity在我的

这是用于重定向用户以确认您的电子邮件页面的Action方法

  [AllowAnonymous]公共ViewResult NewAccountCheckYourEmail(){返回View();} 

我要做的是在用户会话中存储电子邮件,因此,如果用户单击重新发送电子邮件,我将重新发送电子邮件.

我想进行ajax调用,因此当用户单击重新发送"链接时,它将回发到控制器,从用户会话中获取电子邮件,重新发送并重新显示相同的视图.

我不确定该怎么做

让我厌倦的是拨打AJAX:

  $(#ResendEmailLink").click(function(){$ .ajax({url:"/Account/NewAccountCheckYouEmail",数据类型:文本",输入:"POST",成功:功能(数据){$('#testarea').html(一切正常");},错误:功能(){$(#testarea").html("ERROR");}}); 

});

我想让它点击此操作方法:

  [HttpPost][AllowAnonymous]公共异步Task< ActionResult>NewAccountCheckYourEmail(){电子邮件电子邮件=会话[SessionKeys.NewAccountConfirmationEmail.ToString()]作为电子邮件;等待_emailService.SendEmailAsync(email);返回View();} 

但是由于我已经有另一个具有相同名称的Action方法,所以我不能添加它...我想我试图做的事没有多大意义,是否有任何建议实现这一目标的合理方法?

解决方案

正如@Stephen Muecke指出的那样,它返回 Json 数据,因此此基本更改应该有效.

重新发送电子邮件脚本:

  $(#ResendEmailLink").click(function(){$ .ajax({网址:"/Account/ResendEmailToUser",数据类型:"json",输入:"POST",成功:功能(数据){if(data){$('#testarea').html(data.Message)};},错误:功能(){$(#testarea").html("ERROR");}}); 

});

重新发送电子邮件操作方法:

  [HttpPost][AllowAnonymous]公共异步Task< ActionResult>ResendEmailToUser(){电子邮件电子邮件=会话[SessionKeys.NewAccountConfirmationEmail.ToString()]作为电子邮件;等待_emailService.SendEmailAsync(email);var jsonData = new {消息=完成!,我们已重新发送电子邮件"};返回Json(jsonData);} 

This is my first Ajax call, and I am really confused what to do.

I am using ASP.NET MVC, Identity to register users in my website. Once user is registers, I send him an email to confirm their email address.

Here is my register Action Method:

    [HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public async Task<ActionResult> Register(RegisterViewModel model)
    {
        if (ModelState.IsValid)
        {
            var user = new ApplicationUser { UserName = model.Email.Trim(), Email = model.Email.Trim(), FirstName = model.FirstName.Trim(), LastName = model.LastName.Trim() };
            var result = await UserManager.CreateAsync(user, model.Password);
            if (result.Succeeded)
            {
                // Send an email with this link
                string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);
                var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
                Email email = _emailBuilder.BuildConfirmationEmail(new MailAddress(model.Email.Trim(), model.FirstName.Trim() + " " + model.LastName.Trim()), callbackUrl, model.FirstName.Trim());
                Session[SessionKeys.NewAccountConfirmationEmail.ToString()] = email;
                await _emailService.SendEmailAsync(email);

                return RedirectToAction("NewAccountCheckYourEmail");
            }
            AddErrors(result);
        }

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

The register method sends the confirmation email and redirect to NewAccountCheckYourEmail View and user see this page:

and here is the Action method to redirect user to confirm your email page

[AllowAnonymous]
public ViewResult NewAccountCheckYourEmail()
{
    return View();
}

What I want to do is to store the email in user session, so if user click on resend email, I resend the email.

I want to make an ajax call, so when user click on resend link, it posts back to controller, get the email from user session, resend it and redisplay the same view.

And I am not sure how to do this

What I have tired is to make this AJAX call:

$("#ResendEmailLink").click(function () {
$.ajax({
    url: "/Account/NewAccountCheckYouEmail",
    datatype: "text",
    type: "POST",
    success: function (data) {
        $('#testarea').html("All OK");
    },
    error: function () {
        $("#testarea").html("ERROR");
    }
});

});

And I want it to hit this Action Method:

  [HttpPost]
    [AllowAnonymous]
    public async Task<ActionResult> NewAccountCheckYourEmail()
    {
        Email email = Session[SessionKeys.NewAccountConfirmationEmail.ToString()] as Email;
        await _emailService.SendEmailAsync(email);
        return View();
    }

But since I already have another Action method with the same name, I cannot add it... I guess what I am trying to do does not make much sense, any suggestion on a reasonable approach to achieve this?

解决方案

As @Stephen Muecke pointed out to return Json data, so this basic change should work.

Resend Email Script:

$("#ResendEmailLink").click(function () {
$.ajax({
    url: "/Account/ResendEmailToUser",
    datatype:'json',
    type: "POST",
    success: function (data) {

if(data) { $('#testarea').html(data.Message) };

    },
    error: function () {
        $("#testarea").html("ERROR");
    }
});

});

Resend Email Action Method:

[HttpPost]
[AllowAnonymous]
public async Task<ActionResult> ResendEmailToUser()
{

Email email = Session[SessionKeys.NewAccountConfirmationEmail.ToString()] as Email;
await _emailService.SendEmailAsync(email);

var jsonData = new { Message = "Done!, We have Resend the Email" };

return Json(jsonData);

}

这篇关于如何对控制器动作进行Ajax调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆