Pass complex object with redirect in ASP.NET MVC?

后端 未结 3 1075
半阙折子戏
半阙折子戏 2020-12-11 16:14

Hi,

I have a action that looks like this :

[AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Register(AdRegister adRegister         


        
3条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-11 16:58

    One possibility would be to pass the simple properties in the query string:

    return RedirectToAction(
        "Validate", 
        new { 
            foo = adRegister.Foo, 
            bar = adRegister.Bar, 
            ... and so on for all the properties you want to send
        }
    );
    

    Another possibility is to store it in TempData (for the lifetime of the redirect) or Session (for the lifetime of the ASP.NET session):

    TempData["adRegister"] = adRegister;
    return RedirectToAction("Validate");
    

    and then retrieve it from TempData:

    public ActionResult Validate()
    {
        adRegister = TempData["adRegister"] as AdRegister;
        ...
    }
    

    Yet another possibility (and the one I would recommend you) is to persist this object in the POST method in your datastore:

    [AcceptVerbs(HttpVerbs.Post)]
    public ActionResult Register(AdRegister adRegister, IEnumerable files)
    {
        ...
        string id = Repository.Save(adRegister);
        return RedirectToAction("Validate", new { id = adRegister.Id });
    }
    

    and then fetch it from the data store after you redirect:

    public ActionResult Validate(string id)
    {
        AdRegister adRegister = Repository.Get(id);
        ...
    }
    

提交回复
热议问题