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
RedirectToAction
with parameter:
return RedirectToAction("Action","controller", new {@id=id});
If one want to Show error message for [httppost]
then he/she can try by passing an ID using
return RedirectToAction("LogIn", "Security", new { @errorId = 1 });
for Details like this
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 });
}
}
Hope it works fine.
I had this issue as well, and quite a nice way to do it if you are within the same controller is to use named parameters:
return RedirectToAction(actionName: "Action", routeValues: new { id = 99 });
It is also worth noting that you can pass through more than 1 parameter. id will be used to make up part of the URL and any others will be passed through as parameters after a ? in the url and will be UrlEncoded as default.
e.g.
return RedirectToAction("ACTION", "CONTROLLER", new {
id = 99, otherParam = "Something", anotherParam = "OtherStuff"
});
So the url would be:
/CONTROLLER/ACTION/99?otherParam=Something&anotherParam=OtherStuff
These can then be referenced by your controller:
public ActionResult ACTION(string id, string otherParam, string anotherParam) {
// Your code
}
If your need to redirect to an action outside the controller this will work.
return RedirectToAction("ACTION", "CONTROLLER", new { id = 99 });
....
int parameter = Convert.ToInt32(Session["Id"].ToString());
....
return RedirectToAction("ActionName", new { Id = parameter });