Asp.net mvc 对象引用未设置为对象的实例。
我有3种型号: 第一个:Asp.net mvc 对象引用未设置为对象的实例。,asp.net-mvc,asp.net-mvc-4,razor,Asp.net Mvc,Asp.net Mvc 4,Razor,我有3种型号: 第一个: public class CreateFieldModel { public FieldModel fm { get; set; } public CategoryModel cm { get; set; } } 第二个: public class FieldModel { public string field_Name { get; set; } public InputTypeModel
public class CreateFieldModel
{
public FieldModel fm { get; set; }
public CategoryModel cm { get; set; }
}
第二个:
public class FieldModel
{
public string field_Name { get; set; }
public InputTypeModel itm { get; set; }
public string input1 { get; set; }
public string input2 { get; set; }
public string input3 { get; set; }
public string input4 { get; set; }
public List<InputTypeModel> inputs { get; set; }
}
2种方法:
第一个:
public List<InputTypeModel> getInputTypes()
{
var inptypes = edu.InputTypes;
List<InputTypeModel> listInputTypes = new List<InputTypeModel>();
foreach (var inpType in inptypes)
{
listInputTypes.Add(new InputTypeModel { inputTypeName = inpType.Input_Type_Name, inputTypeDesc = inpType.Input_Type_Description });
}
return listInputTypes;
}
当
cfm.fm.inputs=ffm.getInputTypes()时代码>执行它显示“对象引用未设置为对象的实例”。消息。。。我是mvc的初学者。。请帮助在不知道在操作中使用cfm参数真正想要实现什么的情况下,我唯一能建议的是检查空引用并在分配它们之前创建新实例:
[HttpGet]
public ActionResult createNewField(CreateFieldModel cfm, string fcode)
{
FormManagement ffm = new FormManagement();
if (cfm == null)
{
cfm = new CreateFieldModel();
}
if (cfm.fm == null)
{
cfm.fm = new FieldModel();
}
cfm.fm.inputs = ffm.getInputTypes();
return View(cfm);
}
当然,这假设您不依赖通过路由参数传入的数据。如果是,您需要检查为什么没有传入值,但我猜您首先不需要将其作为参数。调用createNewField时,您的cfm很可能为null。使用调试器。在此行上设置断点。查看您的调用堆栈并检查调用函数是否为cfm提供了正确的值。是,它为null。。。我如何解决它?为什么您希望它是非空的?ffm.getInputTypes返回我想要的确切值
[HttpGet]
public ActionResult createNewField(CreateFieldModel cfm, string fcode)
{
FormManagement ffm = new FormManagement();
cfm.fm.inputs = ffm.getInputTypes();
return View(cfm);
}
[HttpGet]
public ActionResult createNewField(CreateFieldModel cfm, string fcode)
{
FormManagement ffm = new FormManagement();
if (cfm == null)
{
cfm = new CreateFieldModel();
}
if (cfm.fm == null)
{
cfm.fm = new FieldModel();
}
cfm.fm.inputs = ffm.getInputTypes();
return View(cfm);
}