Question

I get the value from FormCollection and add in the List.Then the List will assigned to TempData.Now my question is ,How to get the TempData value in Redirect action and add send firstname and last name in Viewbag to view?How can I do this?

 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();
        }
Was it helpful?

Solution

Try this

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();
        }

In view you can access values as

<ul>

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

OTHER TIPS

This is how you store it on viewbag do it

      TempData["UsrName"] = LoginViewModel.LoginDataModel.UserName;

this can be stored in viewData like this

  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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top