繁体   English   中英

C#List nullreference异常ASP.net MVC

[英]C# List nullreference exception ASP.net MVC

在循环内部,我正在尝试将类型为Location的对象添加到List<Location>属性中。

控制器:

 [HttpPost]
 public ActionResult Index([Bind(Include = "CitySearch")]HomeViewModel model)
 {
    List<CityIdentity> ids = null;
    ids = service.GetNamesId(model.CitySearch);

    foreach (var id in ids)
    {
        var loc = service.GetLocation(id.CityId);
        var location = new Location
        {
            CityId = id.CityId,
            Place = loc.Place,
        };
        model.Locations.Add(location);
    }
}

视图模型:

public class HomeViewModel
{
    public string CitySearch { get; set; }

    public List<Location> Locations { get; set; }

}

model的类型为HomeViewModel ,属性Locations的类型为List<Location> model是来自View中提交表单的表单HttpPost操作的实例。

我正在调试,错误发生在model.Locations.Add(location) ,我得到的object reference not set to an instance of an object. 和nullref异常。

任何想法?

任何想法?

是, model变量为null或Locations属性为null。 因此,在访问model.Locations之前,请确保它们不为null。 否则你得到的例外是完全正常的。 您无法在空实例上调用方法。 顺便说一句,您可以使用标准调试技术(在代码中放置断点,在调试模式下运行应用程序并检查变量的值)将导致您得出相同的结论。

现在为什么你的modelmodel.Locations属性为null是一个非常不同的问题。 我猜你提交的表单不包含符合standard naming conventions for binding to a Liststandard naming conventions for binding to a List输入元素。 如果您希望默认模型绑定器能够在POST操作中为模型重新水化,我邀请您熟悉这些约定并尊重它们。

也许不知怎的,你把model作为动作参数,并期望ASP.NET MVC将从某些人自动填充它? 不,这不是ASP.NET MVC的工作原理。 没有魔力。 ASP.NET MVC使用具有严格规则的模型绑定器。 只有您作为动作参数发送的内容才是您可以期待的内容。

根据您的反应和上下文,似乎您的Locations属性当时未初始化,因此您无法在此集合上使用Add方法。 要解决此问题,您需要首先初始化此属性,然后您可以以任何方式操作它。

实现此目的的一种方法是在模型的构造函数中(或您认为合适的任何Locations初始化Locations属性。

所以只需添加这样的东西就可以了:

Locations = new List<Location>();

这会初始化您的属性以使用其方法。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM