You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ASP.NET MVC传递Movie列表到视图时数据丢失、ID返回0问题

问题根因

这是典型的变量名书写笔误导致的数据异常,具体错误点如下:

  • 创建第四个Movie实例customer3后,你没有对customer3的Name、Id属性赋值,反而错误地给之前已经完成赋值的customer1实例重新写入了"spiderman noway home"和Id=04的数据,直接覆盖了customer1原本存储的"amazing spiderman"、Id=03的内容。
  • 你最终传入视图的列表中,第四个元素是从未做过属性赋值的customer3实例。引用类型实例化后未手动赋值时,字符串类型的Name属性默认值为null(页面渲染为空),int类型的Id属性默认值为0,就出现了你看到的"amazing spiderman"丢失、最后一条ID为0的异常输出。
修正方案

将第四个实例的赋值目标从customer1改为customer3即可,修正后的对应代码片段如下:

public ActionResult Index()
{
    Movie customer = new Movie();
    customer.Name = "Avengers";
    customer.Id = 01;
    Movie customer2 = new Movie();
    customer2.Name = "Age of ultron";
    customer2.Id = 02;
    Movie customer1 = new Movie();
    customer1.Name = "amazing spiderman";
    customer1.Id = 03;
    Movie customer3 = new Movie();
    // 修正:赋值对象为customer3,而非已经赋值过的customer1
    customer3.Name = "spiderman noway home";
    customer3.Id = 04;
    List<Movie> list = new List<Movie>();
    list.Add(customer);
    list.Add(customer1);
    list.Add(customer2);
    list.Add(customer3);
    return View(list);
}

建议:变量命名尽量匹配业务语义,比如电影类实例命名用movie1、movie2这类和业务对应的名称,不要复用customer(顾客)这类其他业务的变量名,能有效降低这类低级笔误的出现概率。

内容的提问来源于stack exchange,提问作者CHARU

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.26 23:06:09