在MVC3中获取表单值时出现null引用异常

时间:2012-03-22 17:54:21

标签: asp.net-mvc asp.net-mvc-3 c#-4.0 .net-4.0 nullreferenceexception

这是我的代码:

public ActionResult Register(FormCollection form)
{
    RegisterViewModel registerViewModel = new RegisterViewModel();
    registerViewModel.CaptchaInCache = new CacheWrapper().Get(form["GuidForCaptch"]).ToString();

    // some code here

}

我在下面一行得到空引用异常:

registerViewModel.CaptchaInCache =
    new CacheWrapper().Get(form["GuidForCaptch"]).ToString();

任何人都可以帮我解决这个问题。我在这做错了什么

1 个答案:

答案 0 :(得分:2)

我认为您的应用程序可能过于具体,无法确切知道该怎么做。但是,这应该告诉您问题的确切位置:

var guidForCaptch = form["GuidForCaptch"];

if (guidForCaptch == null)
{
    throw new ArgumentNullException("GuidForCaptch is null");
}

var cacheWrapper = new CacheWrapper().Get(guidForCaptch);

if (cacheWrapper == null)
{
    throw new ArgumentNullException("CacheWrapper is null");
}