Hooman Bahreini
Hooman Bahreini

Reputation: 15559

How to make an ajax call to controller action

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

I am using ASP.NET MVC, Identity to register users in my website. Once the user is registered, 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 the form
    return View(model);
}

The register method sends the confirmation email and redirects to NewAccountCheckYourEmail View and the user sees this page:

enter image description here

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

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

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

I want to make an ajax call, so when the user clicks on resend link, it posts back to the controller, gets the email from the user session, resends it and redisplays the same view.

And I am not sure how to do this

What I have tried 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?

Upvotes: 0

Views: 6498

Answers (1)

Shaiju T
Shaiju T

Reputation: 6609

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

}

Upvotes: 3

Related Questions