Reputation: 331
I'm new to C#, but when I'm submitting a form, I catch the form values and create a new item of it and put it in a list according to the code below:
public ActionResult Movie()
{
int id = Convert.ToInt16(Request.Form["inputmovieid"]);
string name = Request.Form["inputmovietitle"];
int year = Convert.ToInt16(Request.Form["inputproductionyear"]);
List<Movie> movies = new List<Movie>();
Movie movieitem = new Movie(id, name, year);
movies.Add(movieitem);
return View(movies);
}
In a .cshtml-file I then print the created item with a foreach loop, but the problem is that if I submit this form again with new values for a new item, it overwrites the old one in the list.
DESIRED RESULT: When submitting the form again I want a new item to be added to the list without overwriting the old one. Does anyone know how the code above can be modified to solve this?
Upvotes: 0
Views: 2207
Reputation: 22038
You need to store the data into a database of keep track or a list inside a ViewState.
Something like:
public ActionResult Movie()
{
var list = ViewState["MyList"] as List<Movie>;
if(list == null)
{
list = new List<Movie>();
ViewState["MyList"] = list;
}
int id = Convert.ToInt16(Request.Form["inputmovieid"]);
string name = Request.Form["inputmovietitle"];
int year = Convert.ToInt16(Request.Form["inputproductionyear"]);
Movie movieitem = new Movie(id, name, year);
list.Add(movieitem);
return View(list);
}
But my knowledge of asp.net has faded a little, you might need to mark the Movie class as serializable,
[Serializable]
public class Movie
{
...
}
Every time you get a postback/reload, the whole class is reconstructed, so a storing a list into a field won't help you. That's why they invented the viewstate. (hidden formfield sent with the html)
Upvotes: 1