在另一个Action中获取TempData值

时间:2014-05-07 09:08:30

标签: asp.net-mvc asp.net-mvc-4 c#-4.0

我从FormCollection中获取值并添加列表。然后将List分配给TempData.Now我的问题是,如何获取重定向中的TempData值动作并在Viewbag中添加发送名字和姓氏以查看?我该怎么做?

 public ActionResult show(FormCollection form)
        {
            string firstnamevalue = form["firstname"];
            string lastnamevalue = form["lastname"];

            List<string> list = new List<string>();
            list.Add(firstnamevalue);
            list.Add(lastnamevalue);


            TempData["Values"] = list;

            return RedirectToAction("Redirect");
        }

        public ActionResult Redirect()
        {
            //I need to get firstname and lastname here and add to view bag.

            return View();
        }

2 个答案:

答案 0 :(得分:4)

试试这个

public ActionResult show(FormCollection form)
        {
            string firstnamevalue = form["firstname"];
            string lastnamevalue = form["lastname"];

            List<string> list = new List<string>();
            list.Add(firstnamevalue);
            list.Add(lastnamevalue);


            TempData["Values"] = list;

            return RedirectToAction("Redirect");
        }

        public ActionResult Redirect()
        {
            //I need to get firstname and lastname here and add to view bag.
            List<string> lst=(List<string>)TempData["Values"]// cast tempdata to List of string
            ViewBag.Collection=lst;
            return View();
        }

在视图中,您可以访问值

<ul>

   <li>First Name: @ViewBag.Collection[0]</li>
   <li>Last Name: @ViewBag.Collection[1]</li>
</ul>

答案 1 :(得分:0)

这是您将其存储在 viewbag 执行

的方式
      TempData["UsrName"] = LoginViewModel.LoginDataModel.UserName;

这可以像这样存储在viewData中

  public ActionResult LandingPage()
    {  
        ViewData["message"] = TempData["UsrName"].ToString();
        ViewData["person"] =Convert.ToInt32(TempData["UserTypeID"]);
        TempData.Keep();



   //and pass it as parameter like

        String PatID = Convert.ToString(ViewData["message"].ToString());
        int PersonType = Convert.ToInt32(ViewData["person"]);

    }





TempData.Keep()  - should be used to store the value till project stops running, otherwise  if user refreshes the page you will be losing the data on ViewData