I have the list setup in class which is initialized and adds 1 item in the main constructor but adding it from the create view doesn't add it to the list for some reason. Any help will be appreciated.
public class PhoneBase
{
public PhoneBase()
{
DateReleased = DateTime.Now;
PhoneName = string.Empty;
Manufacturer = string.Empty;
}
public int Id { get; set; }
public string PhoneName { get; set; }
public string Manufacturer { get; set; }
public DateTime DateReleased { get; set; }
public int MSRP { get; set; }
public double ScreenSize { get; set; }
}
public class PhonesController : Controller
{
private List<PhoneBase> Phones;
public PhonesController()
{
Phones = new List<PhoneBase>();
var priv = new PhoneBase();
priv.Id = 1;
priv.PhoneName = "Priv";
priv.Manufacturer = "BlackBerry";
priv.DateReleased = new DateTime(2015, 11, 6);
priv.MSRP = 799;
priv.ScreenSize = 5.43;
Phones.Add(priv);
}
public ActionResult Index()
{
return View(Phones);
}
// GET: Phones/Details/5
public ActionResult Details(int id)
{
return View(Phones[id - 1]);
}
Here I insert new list item through Create view using formcollections
public ActionResult Create()
{
return View(new PhoneBase());
}
// POST: Phones/Create
[HttpPost]
public ActionResult Create(FormCollection collection)
{
try
{
// TODO: Add insert logic here
// configure the numbers; they come into the method as strings
int msrp;
double ss;
bool isNumber;
// MSRP first...
isNumber = Int32.TryParse(collection["MSRP"], out msrp);
// next, the screensize...
isNumber = double.TryParse(collection["ScreenSize"], out ss);
// var newItem = new PhoneBase();
Phones.Add(new PhoneBase
{
// configure the unique identifier
Id = Phones.Count + 1,
// configure the string properties
PhoneName = collection["PhoneName"],
Manufacturer = collection["manufacturer"],
// configure the date; it comes into the method as a string
DateReleased = Convert.ToDateTime(collection["DateReleased"]),
MSRP = msrp,
ScreenSize = ss
});
//show results. using the existing Details view
return View("Details", Phones[Phones.Count - 1]);
}
catch
{
return View();
}
}
Viewing the whole list doesn't show any items added through create view.
Because HTTP is stateless!. Phones
is a variable in your PhonesController
and every single http requests to this controller ( to it's various action methods) will create a new instance of this class, thus recreate the Phones
variable again, execute the constructor code to add one Phone item to this collection.
The item you added to the Phones collection in your create action will not be available in the next http request (for Phones/Index) because it has no idea what the previous http request did.
You need to persist the data to be available between multiple requests. You can either store it in a database table / XML file / Temporary storage like Session etc.