剑轩

C# MVC RedirectToAction跳转时候传递参数,Action之间传值

电脑版发表于:2019/1/10 22:30

MVC Action之间传值,页面跳转传值



方法一:路由传值


很简单直接使用 RedirectToAction(string actionName, string controllerName, object routeValues)

这个方法的第三个就是用于传递参数的。

return RedirectToAction("About", new Users() { username = "x", age = 24, address = "j" });

接收:

public ActionResult About(Users user)
{
    return View();
}


传递一个匿名对象也是可以的

return RedirectToAction("About", new { username = "李清照", address = "三国" });

接收:

public ActionResult About(string username, string address)
{
    return View();
}


其实本质也是地址栏传参而已,所以要注意和路由设置冲突问题




方法二:TempData

  public ActionResult News() 
        {
            TempData["name"] = "AJ";

            return RedirectToAction("About");
        }


        public ActionResult About()
        {
            string name = TempData["name"].ToString();

            return View();
        }

tempdata是基于session实现的他是一个临时变量,一次请求中有效,第二次就失效了。
当然如果是一次请求中获取多少也是可以的,所以有些说获取一次会就被销毁的说法是错误的





关于TNBLOG
TNBLOG,技术分享。技术交流:群号677373950
ICP备案 :渝ICP备18016597号-1
App store Android
精彩评论
{{item.replyName}}
{{item.content}}
{{item.time}}
{{subpj.replyName}}
@{{subpj.beReplyName}}{{subpj.content}}
{{subpj.time}}
猜你喜欢