Passing Data Between Different Controller Action Methods

Passing data between different controller action methods

HTTP and redirects

Let's first recap how ASP.NET MVC works:

  1. When an HTTP request comes in, it is matched against a set of routes. If a route matches the request, the controller action corresponding to the route will be invoked.
  2. Before invoking the action method, ASP.NET MVC performs model binding. Model binding is the process of mapping the content of the HTTP request, which is basically just text, to the strongly typed arguments of your action method

Let's also remind ourselves what a redirect is:

An HTTP redirect is a response that the webserver can send to the client, telling the client to look for the requested content under a different URL. The new URL is contained in a Location header that the webserver returns to the client. In ASP.NET MVC, you do an HTTP redirect by returning a RedirectResult from an action.

Passing data

If you were just passing simple values like strings and/or integers, you could pass them as query parameters in the URL in the Location header. This is what would happen if you used something like

return RedirectToAction("ActionName", "Controller", new { arg = updatedResultsDocument });

as others have suggested

The reason that this will not work is that the XDocument is a potentially very complex object. There is no straightforward way for the ASP.NET MVC framework to serialize the document into something that will fit in a URL and then model bind from the URL value back to your XDocument action parameter.

In general, passing the document to the client in order for the client to pass it back to the server on the next request, is a very brittle procedure: it would require all sorts of serialisation and deserialisation and all sorts of things could go wrong. If the document is large, it might also be a substantial waste of bandwidth and might severely impact the performance of your application.

Instead, what you want to do is keep the document around on the server and pass an identifier back to the client. The client then passes the identifier along with the next request and the server retrieves the document using this identifier.

Storing data for retrieval on the next request

So, the question now becomes, where does the server store the document in the meantime? Well, that is for you to decide and the best choice will depend upon your particular scenario. If this document needs to be available in the long run, you may want to store it on disk or in a database. If it contains only transient information, keeping it in the webserver's memory, in the ASP.NET cache or the Session (or TempData, which is more or less the same as the Session in the end) may be the right solution. Either way, you store the document under a key that will allow you to retrieve the document later:

int documentId = _myDocumentRepository.Save(updatedResultsDocument);

and then you return that key to the client:

return RedirectToAction("UpdateConfirmation", "ApplicationPoolController ", new { id = documentId });

When you want to retrieve the document, you simply fetch it based on the key:

 public ActionResult UpdateConfirmation(int id)
{
XDocument doc = _myDocumentRepository.GetById(id);

ConfirmationModel model = new ConfirmationModel(doc);

return View(model);
}

How to pass value from one action to another action having same controller

You can use TempData.You can pass every types of data between to action, whether they are in same controller or not. Your code should be something like it:

    public ActionResult GetMDN(string msisdn)
{
int sngid=10;

TempData["ID"] = sngid;

return RedirectToAction("IIndex");
}

public ActionResult IIndex()
{

int id = Convert.ToInt32(TempData["ID"]);// id will be 10;
}

Passing data between two ActionResults in the same controller rendering different views in asp.net mvc

TempData value is available only to the next request. that means if you set some value to your Details action and you are navigating to the Sortie GET action next, You will be able to retrieve it. But then if you are submitting the form and hitting the Sortie HTTPPost action, It will not be available.

One option is to set the tempdata value again so that it will be accessible in the very next request as well.

public ActionResult Sortie(Int64 id)
{
TempData["codebarre"] = id;
var t = TempData["iddemande"];
TempData["iddemande"] = t;
return View();
}

Another option (better/clean option IMHO) is to pass this value through your form. So instead of setting again to the TempData in the GET action, You keep this TempData value inside a form element and when the form is submitted, this value will be sent to your HttpPost action method. You can add a parameter to your action method to read this.

So in your Sortie view form,

@using (Html.BeginForm())
{
<input type="text" value="@TempData["iddemande"]" name="iddemande" />
<input type="submit" value="submit" />
}

And in your http post action

[HttpPost]        
public ActionResult Sortie(DemandeViewModel postData,int iddemande)
{
// You can use the value of iddemande
// to do : Return something
}

Regarding Session, It should work as long as you are correctly reading it. Session value will be available for all the requests after it is set, until the session ends.

Passing Information Between Controllers in ASP.Net-MVC

Change the call to:

return RedirectToAction("LoginFailed", new { sendFlag = sendStoredInfo });

The controller action method signature could be something like:

public ActionResult LoginFailed(bool sendFlag)
{
...
}

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

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


Related Topics



Leave a reply



Submit