ASP .net MVC 列表未更新

本文关键字:更新 列表 MVC net ASP | 更新日期: 2023-09-27 18:32:06

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

在这里,我通过使用表单集合创建视图插入新列表项

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();
        }
    }

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

ASP .net MVC 列表未更新

因为HTTP是无状态的! PhonesPhonesController中的一个变量,对此控制器的每个 http 请求(对其的各种操作方法)都将创建此类的新实例,从而再次重新创建 Phones 变量,执行构造函数代码以将一个 Phone 项添加到此集合。

在创建操作中添加到 Phones 集合的项在下一个 http 请求(对于电话/索引)中将不可用,因为它不知道上一个 http 请求执行了什么操作。

您需要保留数据以在多个请求之间可用。您可以将其存储在数据库表/XML文件/临时存储(如会话等)中。