2016-01-27 68 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,解决方案在答案的最后一段。 –