我有一个动作,我从一个锚调用,因此,站点/控制器/动作/ID,其中ID是一个int。
稍后,我需要从控制器重定向到相同的动作。
有什么聪明的办法吗?目前我在tempdata中存储ID,但当你 返回后,按f5再次刷新页面,tempdata消失,页面崩溃。
我有一个动作,我从一个锚调用,因此,站点/控制器/动作/ID,其中ID是一个int。
稍后,我需要从控制器重定向到相同的动作。
有什么聪明的办法吗?目前我在tempdata中存储ID,但当你 返回后,按f5再次刷新页面,tempdata消失,页面崩溃。
当前回答
如果你需要重定向到控制器外的动作,这将工作。
return RedirectToAction("ACTION", "CONTROLLER", new { id = 99 });
其他回答
如果有人想显示[httppost]的错误消息,那么他/她可以尝试通过传递一个ID使用
return RedirectToAction("LogIn", "Security", new { @errorId = 1 });
详情如下
public ActionResult LogIn(int? errorId)
{
if (errorId > 0)
{
ViewBag.Error = "UserName Or Password Invalid !";
}
return View();
}
[Httppost]
public ActionResult LogIn(FormCollection form)
{
string user= form["UserId"];
string password = form["Password"];
if (user == "admin" && password == "123")
{
return RedirectToAction("Index", "Admin");
}
else
{
return RedirectToAction("LogIn", "Security", new { @errorId = 1 });
}
}
希望它能正常工作。
您可以将id作为RedirectToAction()方法的routeValues参数的一部分传递。
return RedirectToAction("Action", new { id = 99 });
这将导致重定向到Site/Controller/Action/99。不需要临时或任何类型的视图数据。
//How to use RedirectToAction in MVC
return RedirectToAction("actionName", "ControllerName", routevalue);
例子
return RedirectToAction("Index", "Home", new { id = 2});
Kurt的答案应该是正确的,从我的研究来看,但当我尝试它时,我必须这样做才能让它真正为我工作:
return RedirectToAction( "Main", new RouteValueDictionary(
new { controller = controllerName, action = "Main", Id = Id } ) );
如果我没有在RouteValueDictionary中指定控制器和动作,它就不能工作。
同样,当像这样编码时,第一个参数(Action)似乎被忽略了。因此,如果您只是在Dict中指定控制器,并期望第一个参数指定Action,那么它也不起作用。
如果你稍后再来,先试试Kurt的答案,如果你还有问题,试试这个。
下面的asp.net core 2.1成功了。这可能适用于其他地方。字典ControllerBase.ControllerContext.RouteData.Values可以从action方法中直接访问和写入。也许这是其他解决方案中数据的最终目的地。它还显示了缺省路由数据的来源。
[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
}