我在初始化的類中設置了列表設置,並在主構造函數中添加了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