RedirectToAction with parameter

后端 未结 14 1562
傲寒
傲寒 2020-11-22 08:56

I have an action I call from an anchor thusly, Site/Controller/Action/ID where ID is an int.

Later on I need to redirect to th

相关标签:
14条回答
  • 2020-11-22 09:50

    MVC 4 example...

    Note that you do not always have to pass parameter named ID

    var message = model.UserName + " - thanks for taking yourtime to register on our glorious site. ";
    return RedirectToAction("ThankYou", "Account", new { whatever = message });
    

    And,

    public ActionResult ThankYou(string whatever) {
            ViewBag.message = whatever;
            return View();
    } 
    

    Of course you can assign string to model fields instead of using ViewBag if that is your preference.

    0 讨论(0)
  • 2020-11-22 09:51

    The following succeeded with asp.net core 2.1. It may apply elsewhere. The dictionary ControllerBase.ControllerContext.RouteData.Values is directly accessible and writable from within the action method. Perhaps this is the ultimate destination of the data in the other solutions. It also shows where the default routing data comes from.

    [Route("/to/{email?}")]
    public IActionResult ToAction(string email)
    {
        return View("To", email);
    }
    [Route("/from")]
    public IActionResult FromAction()
    {
        ControllerContext.RouteData.Values.Add("email", "mike@myemail.com");
        return RedirectToAction(nameof(ToAction));
             // will redirect to /to/mike@myemail.com
    }
    [Route("/FromAnother/{email?}")]`
    public IActionResult FromAnotherAction(string email)
    {
        return RedirectToAction(nameof(ToAction));
             // will redirect to /to/<whatever the email param says>
             // no need to specify the route part explicitly
    }
    
    0 讨论(0)
提交回复
热议问题