lucky
lucky

Reputation: 65

How to pass thw Viewdata to all the views in my controller?

i have a dropdown list which select a value

    [AcceptVerbs(HttpVerbs.Post)]
    public ActionResult Screenname(FormCollection collection)
    {
        Viewdata["screenname"] = collection[0];

        return RedirectToAction("Index", new { ScreenName = ViewData["screenname"] });
    }

then i want to access this ViewData in other actions like this

   [AcceptVerbs(HttpVerbs.Post)]
    public ActionResult Create(FormCollection collection, string screenname)
    {
        try
        {
            /// thats my dataobject which creates 

            DataObj.SaveData(Guid.Empty, collection, screenname);

            return RedirectToAction("Index", new { ScreenName = ViewData["screenname"] });
        }
        catch
        {
            return View("Error");
        }
    }

where index looks like this ...

    public ActionResult Index(string ScreenName)
    {
        ///thats my list 
        GetTable = new GetDataTable(ScreenName);

        return View(GetTable);
    }

First when i select the value and index gets executed properly.... but when i try to access the viewdata again it doesn't contain the value so anybody if please can help ... or alternate method to save and retrieve data .

Upvotes: 0

Views: 1623

Answers (3)

lucky
lucky

Reputation: 65

I used a view to take the data from the user and then saved it to a static variable and then used this variable to pass the data to all the other views .

Thanks anyways

Upvotes: -2

Franci Penov
Franci Penov

Reputation: 76001

The ViewData object is specific for the particular action that is executing. To pass data between actions, use TempData. more on the difference between the two on MSDN.

You can also directly write to the session state through the Controller.Session property.

Upvotes: 2

womp
womp

Reputation: 116987

This has actually been covered quite often here. The solution for now is to use TempData to save the data you need before you use RedirectToAction().

If you do a search for "RedirectToAction" you'll find a number of posts covering this topic, such as this one.

The next official release of the framework will fix this.

Upvotes: 1

Related Questions