ASP .net MVC 列表未更新

ASP .net MVC List not updating

我在 class 中设置了列表,它已初始化并在主构造函数中添加了 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]);
    }

这里我通过 Create view using 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();
        }
    }

查看整个列表不会显示通过创建视图添加的任何项目。

因为HTTP 是无状态的!Phones 是你的 PhonesController 中的一个变量,每个对这个控制器的 http 请求( 到它的各种操作方法 )都会创建这个 class,因此再次重新创建 Phones 变量,执行构造函数代码以向此集合添加一个 Phone 项。

您在创建操作中添加到 Phones 集合的项目在下一个 http 请求(对于 Phones/Index)中将不可用,因为它不知道之前的 http 请求做了什么。

您需要保留数据以便在多个请求之间可用。您可以将其存储在数据库中 table / XML 文件 / 临时存储,如 Session 等