MVC RedirectToAction() any way to pass object to t

2019-05-18 17:46发布

问题:

The populated catList is always Count=0 when the code jumps to CreateProduct() so I take it it does not get delivered. Considering RouteValueDictionary does not do this ? Any other way?

       public ActionResult GetCats(int CatID)
    {

        List<Category> catList = new List<Category>();

        if (CatID >= 0 )
        {

            catList = context.Categories.Where(x => x.PCATID == CatID).ToList();
        }


        return RedirectToAction("CreateProduct", "Admin", new { catList });
    }





public ActionResult CreateProduct(List<Category> catList) {      }

回答1:

You are actually trying to use controllers to do data access.

Move the "GetCats" data retrieval into your business layer (Service object, Repository, whatever suits you).

Then, CreateProduct will need to be there twice (2 signatures). One with no parameters in which you are going to call "GetCats" from your business layer and send it to the view.

The other implementation is going to be the flagged with the HttpPostAttribute and will contain in parameters all the necessary information to create a cat.

That's all. Simple and easy.



回答2:

You could place any items that you need in TempData then call RedirectToAction.



回答3:

RedirectToAction simply returns a "302" code to the browser with the URL to redirect to. When this happens your browser performs a GET with that URL.

Your RouteValues need to be simple. You can't really pass complex object or collections using a route value.



回答4:

if you don't care about the browser url changing you could just

return CreateProduct(catList)