我在类中进行了列表设置初始化并在主构造函数中添加了1个项目,但是从创建视图中添加它并不会因为某些原因将其添加到列表中。任何帮助将不胜感激。
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]);
}
这里我使用formcollections
通过Create view插入新的列表项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();
}
}
查看整个列表并不会显示通过创建视图添加的任何项目。
答案 0 :(得分:2)
因为 HTTP是无状态的!。 Phones
是PhonesController
中的变量,每个对该控制器的http请求(到它的各种操作方法)都会创建此类的新实例,因此,再次重新创建Phones
变量,执行构造函数代码将一个Phone项添加到此集合。
您在创建操作中添加到Phones集合的项目将无法在下一个http请求中使用(对于电话/索引),因为它不知道之前的http请求是做什么的。< / p>
您需要保持数据在多个请求之间可用。您可以将其存储在数据库表/ XML文件/临时存储(如会话等)中。