[英]Assign value to list property of a class
Please check the controller and model bellow. 请检查下面的控制器和型号。 I am trying to add data to a list property of class
CreateProductPage_IniViewData
but problem is when i try to do it normally in controller it says - 我正在尝试将数据添加到类
CreateProductPage_IniViewData
的列表属性中,但是问题是,当我尝试在控制器中正常执行操作时,它说-
System.NullReferenceException: 'Object reference not set to an instance of an object.'
System.NullReferenceException:'对象引用未设置为对象的实例。
So whats wrong i am doing? 那我在做什么错? Any idea?
任何想法?
Model: 模型:
namespace Demo.ViewModels
{
public class CreateProductPage_IniViewData
{
public string StoreUrl { get; set; }
public List<ProductGroupFake> productGroup { get; set; }
}
public class ProductGroupFake
{
public string GroupName { get; set; }
}
}
Controller: 控制器:
public IActionResult Index()
{
var finalData = new CreateProductPage_IniViewData();
finalData.productGroup.Add(new ProductGroupFake { GroupName = "foo", });
return View();
}
in here: 在这里:
var finalData = new CreateProductPage_IniViewData();
the productGroup
inside new CreateProductPage_IniViewData
is not initialized. new CreateProductPage_IniViewData
内部的productGroup
未初始化。 simply set it a default value like this: 只需将其设置为如下所示的默认值:
public class CreateProductPage_IniViewData
{
public string StoreUrl { get; set; }
public List<ProductGroupFake> productGroup { get; set; } = new List<ProductGroupFake>();
}
Or just initialize it before adding to it: 或者只是在将其添加之前对其进行初始化:
var finalData = new CreateProductPage_IniViewData();
finalData.productGroup = new List<ProductGroupFake>();
finalData.productGroup.Add(new ProductGroupFake { GroupName = "foo"});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.