RedirectToAction with parameter

后端 未结 14 1560
傲寒
傲寒 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:27

    RedirectToAction with parameter:

    return RedirectToAction("Action","controller", new {@id=id});
    
    0 讨论(0)
  • 2020-11-22 09:27

    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.

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

    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 });
    
    0 讨论(0)
  • 2020-11-22 09:30

    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
              }
    
    0 讨论(0)
  • 2020-11-22 09:31

    If your need to redirect to an action outside the controller this will work.

    return RedirectToAction("ACTION", "CONTROLLER", new { id = 99 });
    
    0 讨论(0)
  • 2020-11-22 09:32

    ....

    int parameter = Convert.ToInt32(Session["Id"].ToString());
    

    ....

    return RedirectToAction("ActionName", new { Id = parameter });
    
    0 讨论(0)
提交回复
热议问题