[英]MVC return View(model) Cannot perform runtime binding on a null reference
我真的不清楚。
代码看起来像这样
public ActionResult ViewDevice(string id)
{
FooObject model = new FooObject();
if (id == null)
return View(model);
model = SomeMethodThatReturnsFooObject(id);
return View(model);
}
在我看来,我检查Model是否为null,所以我假设这是可行的。
当ID不为null时,我得到由FooObject.Fill填充的模型变量,它在View上显示得很好。
当ID为null时,控制器会在运行时收到此错误:
“无法对空引用执行运行时绑定”。
有什么原因吗?
您不需要像下面这样返回空的模型对象:
public ActionResult ViewDevice(string id)
{
if (id == null)
return View();
FooObject model = SomeMethodThatReturnsFooObject(id);
return View(model);
}
U can use this,
public ActionResult ViewDevice(string ?id)
{
long _id = id ?? 0;
if(_id > 0)
{
FooObject model = SomeMethodThatReturnsFooObject(id);
return View(model);
}
return view();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.