【问题标题】:Cannot perform runtime binding on a null reference无法对空引用执行运行时绑定
【发布时间】: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


    【解决方案1】:

    您可以将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 }
    }
    

    【讨论】:

      猜你喜欢
      • 2020-02-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多