2016-01-27 106 views
-2

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

查看整個列表不顯示通過添加創建視圖的任何物品通過創建視圖。

+0

您是如何查看整個列表的?有沒有一個單獨的行動方法?如果是,那看起來如何?如果否,並且它是詳細信息視圖,則您將單個項目從電話列表傳遞到視圖。你如何期待它顯示所有項目? – Shyju

+0

@Shyju我添加了大部分內容。我認爲問題出在創建視圖操作方法中,這就是爲什麼沒有包含。我現在更新了它。 – Sobasofly

+1

您需要在諸如數據庫之類的地方存儲電話。 – halit

回答

2

因爲HTTP是無狀態的!Phones是您的PhonesController中的一個變量,並且對該控制器的每個單個http請求(以其各種操作方法)將創建此類的新實例,從而再次重新創建Phones變量,執行構造函數代碼以將一個Phone項添加到這個集合。

您在創建操作中添加到Phones集合中的項目在下一個http請求(電話/索引)中將不可用,因爲它不知道以前的http請求做了什麼。

您需要保持數據在多個請求之間可用。您可以將其存儲在數據庫表/ XML文件/臨時存儲中,如會話等。

+0

你爲什麼不展示解決方案?你並沒有真正幫助他。 –

+1

@JohnPeters,解決方案在答案的最後一段。 –