Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

asp.net mvc 3 - 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 });
    }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...