【发布时间】:2012-09-20 16:53:28
【问题描述】:
我有一个包含 id 的详细信息页面,但如果我没有在 http://mysite.com/Detail?id=131 中传递 id 或者我只是输入 http://mysite.com/Detail 我会收到错误
Cannot perform runtime binding on a null reference
我想在此显示自定义错误消息,该怎么做?
【问题讨论】:
标签: asp.net-mvc
我有一个包含 id 的详细信息页面,但如果我没有在 http://mysite.com/Detail?id=131 中传递 id 或者我只是输入 http://mysite.com/Detail 我会收到错误
Cannot perform runtime binding on a null reference
我想在此显示自定义错误消息,该怎么做?
【问题讨论】:
标签: asp.net-mvc
您可以将id 参数设为可空,并像这样检查它:
public ActionResult Detail(int? id)
{
if (id.HasValue() == false)
{ return custom error message }
}
或者您也可以使用[Required(ErrorMessage = "error message")] 注释您的可为空的 id 以获得客户端验证。并执行服务器验证,如:
public ActionResult Detail(int? id)
{
if (ModelState.IsValid == false)
{ return custom error message }
}
【讨论】: