Administrateur
Administrateur

Reputation: 901

How to make control values persist across requests?

I'm using ViewData to pass a List<string> to my View:

// Controller:
ViewData["myList"] = new SelectList(new List<string>(new[] "AAA", "BBB", "CCC" }));

I use this List to populate a ListBox:

// View:
@Html.ListBox("myList")

On Post I retrieve the selected items, like so:

// Controller:
string myList = form["myList"]

So far so good, but the selected items are all cleared on Post.
How do I make selected items persist across requests?

Upvotes: 2

Views: 2382

Answers (4)

Brent Mannering
Brent Mannering

Reputation: 2316

As mentioned already, MVC has no ViewState mechanism, so the values that you want rendered in the view have to be instantiated with each request.

Here is a fairly crude example, but should outline what you need to do:

public ActionResult Index()
{
    ViewData["myList"] = GetSelectList();
    return View();
}

[HttpPost]
public ActionResult Index(FormCollection form)
{
    ViewData["myList"] = GetSelectList(form["myList"]);
    return View();
}

private MultiSelectList GetSelectList(string selected = "")
{
    var selectedValues = selected.Split(',');
    return new MultiSelectList(new List<string>(new[] { "AAA", "BBB", "CCC" }), selectedValues);
}

View markup

@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>

@using (Html.BeginForm()) {
    @Html.ListBox("myList")
    <input type="submit" value="Submit" />
}

Upvotes: 1

Christian Phillips
Christian Phillips

Reputation: 18759

You could add the data into a session object.

Session["myList"] = your List<string>

When you need to pull it back out of the session, use...

List<string> myList = (List<string>)Session["myList"];

using your code,

var selectList = new SelectList(new List<string> {"AAA", "BBB", "CCC"});
Session["myList"] = selectList; 

Then, if you want to assign it in your controller to ViewData...

ViewData["myList"] = (SelectList)Session["myList"]; //may not need the cast.

@Html.ListBox("myList")

Upvotes: 0

Shashank Chaturvedi
Shashank Chaturvedi

Reputation: 2793

Since MVC does not have any mechanism like viewstate or controlstate the data can not be persisted across the requests automatically. So with every request you will have to create the page as you want it to be delivered. On post when you get the selected item, you will have to send the value to the view to be selected for the next load.

Here is a link where you can get a working code.

Upvotes: 1

COLD TOLD
COLD TOLD

Reputation: 13579

If you are using listbox which means you can select several you have to use MultiselectList

ViewData["myList"] = new MultiSelectList(new List<string>(new[] "AAA", "BBB", "CCC" }));

Upvotes: 0

Related Questions