How would you pass the model from an (GetDate) action to another (ProcessP) action via RedirectAction method?
Here's the source code:
[HttpPost]
public ActionResult GetDate(FormCollection values, DateParameter newDateParameter)
{
if (ModelState.IsValid)
{
return RedirectToAction("ProcessP");
}
else
{
return View(newDateParameter);
}
}
public ActionResult ProcessP()
{
//Access the model from GetDate here??
var model = (from p in _db.blah
orderby p.CreateDate descending
select p).Take(10);
return View(model);
}
How to pass data from one action method to another action method? Sometimes, we may need to pass some data from one action method to another while redirecting the user to another action method. In this case, we can pass certain data through the RedirectToAction method by objectParamter.
There are a number of ways in which you can pass parameters to action methods in ASP.NET Core MVC. You can pass them via a URL, a query string, a request header, a request body, or even a form. This article talks about all of these ways, and illustrates them with code examples.
You can use TempData to pass the object. This worked well, Thanks Eranga. One potential pitfall is that the object can be disposed before it gets used in the view if you have a overridden definition for Dispose in your controller(something VS tends to add in with its auto generated CRUD code).
ViewBag is a very well known way to pass the data from Controller to View & even View to View. ViewBag uses the dynamic feature that was added in C# 4.0. We can say ViewBag=ViewData + Dynamic wrapper around the ViewData dictionary. Let's see how it is used.
If you need to pass data from one action to another one option is to utilize TempData. For example within GetDate you could add data to the session as follows:
TempData["Key"] = YourData
And then perform the redirect. Within ProcessP you can access the data utilizing the key you previously used:
var whatever = TempData["Key"];
For a decent read, I would recommend reading through this thread: ASP.NET MVC - TempData - Good or bad practice
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With