Search code examples
c#asp.net-mvcasp.net-mvc-5asp.net-ajaxajaxform

Pass a variable from a view to a controller action method and then to another method in the same ASP.NET MVC controller


One of my views get a token from an API when customer places an order. I would like to pass that token variable to an action method in a controller. Once it gets to that action method I need to pass it to another method inside the same controller. How do I accomplish that?

This is what I have so far - this is the view:

<script type="text/javascript">

document.addEventListener('jrig.begin', function () {
  
    jrig.events.on('bag.confirmed', (bagConfirmResponse) => {
                                
        console.log('This is the token number: ' + bagConfirmResponse.token);
                                                                                           
        //Go to the thank you page
        var url = '/purchase/thank-you/order/' + bagConfirmResponse.token;
        var bagConfirmResponsetoken = bagConfirmResponse.token;

        //Testing passing the token variable to the PurchaseController.cs
        $.ajax({
            type: "POST",
            url: "/Purchase/GetTokenFromView",
            data: '{Token: ' + JSON.stringify(bagConfirmResponsetoken) + '}',
            contentType: "application/json; charset=utf-8",
            dataType: "json",
           
        });

        window.location.href = url;
    });
});    
</script>

Then once the token variable makes it to the PurchaseController it gets passed to this JsonResult below:

public JsonResult GetTokenFromView(string Token)
{
    ViewBag.PassedToken = Token;
    return Json(Token);

    // I have tried redirectToAction as well but the value becomes null.
}

I want to be able to create a view bag there so that I can pass that value for the token to the ActionResult that comes after the GetTokenFromView JSON result which is the ActionResult "Thank you".

public ActionResult Thankyou(string slug, string Token, string email)
{
    slug = "thank-you";
    Console.Write(Token);
    //Token = ViewBag.PassedToken;
    var savedToken = Token;
    Console.Write(savedToken);

    var url = "https://application.ecomapi.com/api/purchases/" + savedToken;
    var httpRequest = (HttpWebRequest)WebRequest.Create(url);

    return View();
}

The view bag that I created to pass the token, no longer has a value once we enter the "Thankyou" action result. So there is no way for me to reference it anymore.

Is there a way I can maybe pass that piece of data a better way. Perhaps even pass it from view to the controller without having to use ajax ?

I have tried to pass it directly from the view to the thankyou method but when I do that it nulls out the value once the program gets to where it needs to call that token. During debugging it jumps back and forth from JsonResult GetTokenFromView to ActionResult Thankyou eventually making the value null again when I need it, so I figured I don't pass it directly from view to thankyou, but pass it to another method first instead.

Thanks.


Solution

  • You can use ViewData or TempData to persist your variables from one Controller action to another:

    public JsonResult GetTokenFromView(string Token)
    {
        ViewData["PassedToken"] = Token;
        return Json(Token);
    
        // I have tried redirectToAction as well but the value becomes null.
    }
    

    And access it in your Thankyou method like this:

    public ActionResult Thankyou(string slug, string Token, string email)
    {
        slug = "thank-you";
        Console.Write(Token);
        //Token = ViewBag.PassedToken;
        //Get your ViewData variables here
        if (ViewData["PassedToken"] != null)
        {
          Token=ViewData["PassedToken"];
        }
        var savedToken = Token;
        Console.Write(savedToken);
    
        var url = "https://application.ecomapi.com/api/purchases/" + savedToken;
        var httpRequest = (HttpWebRequest)WebRequest.Create(url);
    
        return View();
    }