在一个循环中,我试图添加一个类型为 Location
的对象到 List<Location>
属性(property)。
Controller :
[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);
}
}
View 模型:
public class HomeViewModel
{
public string CitySearch { get; set; }
public List<Location> Locations { get; set; }
}
model
类型为 HomeViewModel
和属性(property)Locations
类型为 List<Location>
. model
是来自表格 HttpPost
的实例在 View 中提交表单的操作。
我正在调试,错误发生在 model.Locations.Add(location)
我得到 object reference not set to an instance of an object.
和 nullref 异常。
有什么想法吗?
最佳答案
根据您的 react 和上下文,您的 Locations
属性似乎当时未初始化,因此您不能在此集合上使用方法 Add
.要克服这个问题,您需要先初始化此属性,然后您可以根据需要以任何方式操作它。
实现此目的的一种方法是在模型的构造函数中(或您认为合适的任何地方)初始化您的 Locations
属性。
所以只要添加这样的东西就可以了:
Locations = new List<Location>();
这会初始化您的属性,足以使用它的方法。
关于C# List nullreference 异常 ASP.net MVC,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14224589/