Home How to make an ajax call to controller action
Reply: 1

How to make an ajax call to controller action

Sarhang
1#
Sarhang Published in 2017-12-06 11:13:03Z

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

stom
2#
stom Reply to 2017-12-06 11:37:20Z

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);

}
You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.343944 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO