对象引用未设置为对象的实例 #3

4

我在方法开始时遇到了对象引用错误。

例如:

259: public ActionResult ShowAddress(FormCollection formCollection)
260: {

在上面的示例中,我遇到了错误,错误行号为260。

当询问特定于语言的问题时,请明确指定您所询问的语言。 - anon
@Prasad:你认为每个人都在使用和你一样的编程语言吗?同样的框架或平台?同样的版本? - Cerebrus
糟糕,我忘记指定了。 这段代码来自MVC控制器。 - Prasad
以下是我得到异常的方法的完整代码:[AcceptVerbs(HttpVerbs.Post)] public ActionResult ShowAddress(FormCollection formCollection) { long _userId= long.Parse(formCollection["UserId"].ToString()); UserDetails _userDetails = _userDAL.GetUserDetails(_userId); if(!string.IsNullOrEmpty(_userDetails.Address1)) return RedirectToAction("GetAddress", "User"); else return View();} - Prasad
我不确定为什么读者会对糟糕的问题或缺失的信息感到愤怒。这会对提问者造成更大的伤害。要么帮助提问者,要么就不要回答。 - shannon
显示剩余3条评论
2个回答

2

以下是来自问题评论的代码:

259: public ActionResult ShowAddress(FormCollection formCollection) { 
260:   long _userId= long.Parse(formCollection["UserId"].ToString()); 
261:   UserDetails _userDetails = _userDAL.GetUserDetails(_userId); 
262:   if(!string.IsNullOrEmpty(_userDetails.Address1)) return  RedirectToAction("GetAddress", "User"); else return View(); }

如果你在第260行看到了NullReferenceException,那么formCollection或者formCollection["UserId"]的结果可能为null。你需要在代码中考虑到这一点。例如,你可以执行以下操作。
public ActionResult ShowAddress(FormCollection formCollection) {
  if ( null == formCollection ) { 
    return View();
  }
  object obj = formCollection["UserId"];
  if ( null == obj ) {  
    return View();
  }
  long _userId = long.Parse(obj.ToString());
  ...
}

考虑以下代码: 259: public ActionResult ShowAddress(FormCollection formCollection) 260: { 261: long _userId= long.Parse(formCollection["UserId"].ToString());我在第260行出现错误,而不是在访问formcollection时。 - Prasad
@Prasad,你为什么认为是第260行?你是从异常信息中获取的行号吗?如果是这样,可能由于一个从0开始,另一个从1开始,所以异常和编辑器具有不同的行号。此外,你是否已经附加了调试器以查看这里实际上是什么为空? - JaredPar
堆栈跟踪:在C:\ My Projects \ MVCApp \ Controllers \ UserController.cs的MVCApp.Controllers.UserController.ShowAddress(FormCollection formCollection)中:第260行 在lambda_method(ExecutionScope,ControllerBase,Object [])处 在System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller,Object [] parameters)处 - Prasad

1

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接