Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

send data between actions with redirectAction and prg pattern

how can i send data between actions with redirectAction??

I am using PRG pattern. And I want to make something like that

[HttpGet]
    [ActionName("Success")]
    public ActionResult Success(PersonalDataViewModel model)
    {
        //model ko
        if (model == null)
            return RedirectToAction("Index", "Account");

        //model OK
        return View(model);
    }

    [HttpPost]
    [ExportModelStateToTempData]
    [ActionName("Success")]
    public ActionResult SuccessProcess(PersonalDataViewModel model)
    {

        if (!ModelState.IsValid)
        {
            ModelState.AddModelError("", "Error");
            return RedirectToAction("Index", "Account");
        }

        //model OK
        return RedirectToAction("Success", new PersonalDataViewModel() { BadgeData = this.GetBadgeData });
    }
like image 923
Pedre Avatar asked Dec 20 '22 21:12

Pedre


1 Answers

When redirect you can only pass query string values. Not entire complex objects:

return RedirectToAction("Success", new {
    prop1 = model.Prop1,
    prop2 = model.Prop2,
    ...
});

This works only with scalar values. So you need to ensure that you include every property that you need in the query string, otherwise it will be lost in the redirect.

Another possibility is to persist your model somewhere on the server (like a database or something) and when redirecting only pass the id which will allow to retrieve the model back:

int id = StoreModel(model);
return RedirectToAction("Success", new { id = id });

and inside the Success action retrieve the model back:

public ActionResult Success(int id)
{
    var model = GetModel(id);
    ...
}

Yet another possibility is to use TempData although personally I don't recommend it:

TempData["model"] = model;
return RedirectToAction("Success");

and inside the Success action fetch it from TempData:

var model = TempData["model"] as PersonalDataViewModel;
like image 100
Darin Dimitrov Avatar answered Mar 07 '23 03:03

Darin Dimitrov