How to pass a parameter from one Action to another Action in the same Controller

Asked

Viewed 679 times

2

I need to send a parameter from one action to another action in the same controller, but the parameter is "reset". How can I do this? Down with the code I’m making:

[Authorize]
public class ItemMaloteController : Controller
{
    public IActionResult Index(Guid id)
    {
        ViewBag.ItemsMaloteList = _itemMaloteRepository.GetAll()
                                       .Where(x => x.MaloteId.Equals(id)).ToList();

        ViewBag.Malote = _maloteRepository.GetAll()
                         .Where(x => x.Id.Equals(id)).ToList();

        ViewBag.Curso = _cursoRepository.GetAll().ToList();
        ViewBag.Documentos = _documentosRepository.GetAll();
        ViewBag.MaloteId = id;

        return View();
     }

     public IActionResult Create(ItemMalote itemMalote)
        {
            if (!ModelState.IsValid)
                return NotFound();

            itemMalote.Id = Guid.NewGuid();            
            _itemMaloteRepository.Register(itemMalote);
            _itemMaloteRepository.SaveChanges();

            var maloteId = _itemMaloteRepository.GetMalote(itemMalote.MaloteId).Select(x => x.MaloteId).ToList();            

            //Aqui eu chamo minha action "Index" e passo o parametro
            return RedirectToAction("Index", maloteId);
        }
}

It happens that when it arrives again in the action "Index" the parameter arrives "zeroed". I tried to pass via Tempdata, but the same happens.

2 answers

2


return RedirectToAction("Index", new { id = maloteId });

With the above solution given by Pedro you will have to redirect this:

/Controller/Index/maloteId

But there are more overloads to the method Redirecttoaction. If you need to redirect to another controller’s action, for example, you can use it this way:

return RedirectToAction("MinhaAction", "MinhaController", id);

But in this issue of Soen I saw that it is still possible not to be redirected and you can use also this way, using the Routevaluedictionary:

return RedirectToAction("SuaAction", new RouteValueDictionary(
       new { controller = "SuaController", action = "SuaAction", Id = id }));

Or you can just do that too:

return Index(id);

1

Create an anonymous type with the parameter id that your Action Index is waiting:

//Aqui eu chamo minha action "Index" e passo o parametro
return RedirectToAction("Index", new { id = maloteId });
  • Only the Return was missing :)

  • True, I had forgotten... I have already edited the answer. Thank you very much!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.