我在初始化的类中设置了列表设置,并在主构造函数中添加了1个项目,但是从创建视图添加它并不会因为某些原因将它添加到列表中。任何帮助将不胜感激。ASP .net MVC List not updating
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
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();
}
}
查看整个列表不显示通过添加创建视图的任何物品通过创建视图。
您是如何查看整个列表的?有没有一个单独的行动方法?如果是,那看起来如何?如果否,并且它是详细信息视图,则您将单个项目从电话列表传递到视图。你如何期待它显示所有项目? – Shyju
@Shyju我添加了大部分内容。我认为问题出在创建视图操作方法中,这就是为什么没有包含。我现在更新了它。 – Sobasofly
您需要在诸如数据库之类的地方存储电话。 – halit