'对象引用未设置为对象的实例' - 这是什么意思?

时间:2012-02-22 14:20:02

标签: c# sql-server asp.net-mvc

我正在创建一个包含“关联”数据的MVC 3应用程序,但是我还需要能够通过应用程序删除这些“关联者”。我正在使用Delete ActionResult,但每次我尝试删除一个条目时,都会收到以下服务器错误:

Object reference not set to an instance of an object.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. 

Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.

Source Error: 


Line 14:         <div class="form-grid-1">
Line 15:             <div class="display-label">@Html.LabelFor(model => model.FirstName)</div>
Line 16:             <div class="display-field">@Model.FirstName</div>
Line 17:         </div>
Line 18: 

Source File: c:\Users\Jackie\Documents\Visual Studio 2010\Projects\Associate Tracker versions\Associate Tracker v5\LoginFormExample\Views\Associate\Delete.cshtml    Line: 16 

Stack Trace: 


[NullReferenceException: Object reference not set to an instance of an object.]
   ASP._Page_Views_Associate_Delete_cshtml.Execute() in c:\Users\Jaskharan Shoker\Documents\Visual Studio 2010\Projects\Associate Tracker versions\Associate Tracker v5\LoginFormExample\Views\Associate\Delete.cshtml:16
   System.Web.WebPages.WebPageBase.ExecutePageHierarchy() +207
   System.Web.Mvc.WebViewPage.ExecutePageHierarchy() +81
   System.Web.WebPages.StartPage.RunPage() +19
   System.Web.WebPages.StartPage.ExecutePageHierarchy() +65
   System.Web.WebPages.WebPageBase.ExecutePageHierarchy(WebPageContext pageContext, TextWriter writer, WebPageRenderingBase startPage) +76
   System.Web.Mvc.RazorView.RenderView(ViewContext viewContext, TextWriter writer, Object instance) +220
   System.Web.Mvc.BuildManagerCompiledView.Render(ViewContext viewContext, TextWriter writer) +115
   System.Web.Mvc.ViewResultBase.ExecuteResult(ControllerContext context) +303
   System.Web.Mvc.ControllerActionInvoker.InvokeActionResult(ControllerContext controllerContext, ActionResult actionResult) +13
   System.Web.Mvc.<>c__DisplayClass1c.<InvokeActionResultWithFilters>b__19() +23
   System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilter(IResultFilter filter, ResultExecutingContext preContext, Func`1 continuation) +260
   System.Web.Mvc.<>c__DisplayClass1e.<InvokeActionResultWithFilters>b__1b() +19
   System.Web.Mvc.ControllerActionInvoker.InvokeActionResultWithFilters(ControllerContext controllerContext, IList`1 filters, ActionResult actionResult) +177
   System.Web.Mvc.ControllerActionInvoker.InvokeAction(ControllerContext controllerContext, String actionName) +343
   System.Web.Mvc.Controller.ExecuteCore() +116
   System.Web.Mvc.ControllerBase.Execute(RequestContext requestContext) +97
   System.Web.Mvc.ControllerBase.System.Web.Mvc.IController.Execute(RequestContext requestContext) +10
   System.Web.Mvc.<>c__DisplayClassb.<BeginProcessRequest>b__5() +37
   System.Web.Mvc.Async.<>c__DisplayClass1.<MakeVoidDelegate>b__0() +21
   System.Web.Mvc.Async.<>c__DisplayClass8`1.<BeginSynchronous>b__7(IAsyncResult _) +12
   System.Web.Mvc.Async.WrappedAsyncResult`1.End() +62
   System.Web.Mvc.<>c__DisplayClasse.<EndProcessRequest>b__d() +50
   System.Web.Mvc.SecurityUtil.<GetCallInAppTrustThunk>b__0(Action f) +7
   System.Web.Mvc.SecurityUtil.ProcessInApplicationTrust(Action action) +22
   System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +60
   System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +9
   System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +8969117
   System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +184

控制器:

//
// GET: /Associate/Delete/AssociateId
public ActionResult Delete(int id)
{
    using (var db = new AssociateDBEntities())
    {
        return View(db.Associates.Find(id));
        }
    }

//
// POST: /Associate/Delete/AssociateId
[HttpPost]
public ActionResult Delete(int id, Associate associate)
{
        try
        {
            using (var db = new AssociateDBEntities())
            {
                db.Entry(associate).State = System.Data.EntityState.Deleted;
                db.SaveChanges();
            }
            return RedirectToAction("ViewAll");
        }
        catch
        {
            return View();
        }

'删除'视图

@model LoginFormExample.Models.Associate

@{
    ViewBag.Title = "Delete";
}

<h2>Delete</h2>
<h3>Are you sure you want to delete this associate?</h3>
<fieldset>
    <legend>Associate</legend>

        @Html.HiddenFor(model => model.AssociateId)

        <div class="form-grid-1">
            <div class="display-label">@Html.LabelFor(model => model.FirstName)</div>
            <div class="display-field">@Model.FirstName</div>
        </div>

        <div class="form-grid-2">
            <div class="display-label">@Html.LabelFor(model => model.LastName)</div>
            <div class="display-field">@Model.LastName</div>
        </div>

        <div class="form-grid-1">
             <div class="display-label">@Html.LabelFor(model => model.Email)</div>
            <div class="display-field">@Model.Email</div>
        </div>

        <div class="form-grid-2">
            <div class="display-label">@Html.LabelFor(model => model.AddressLine1)     </div>
            <div class="display-field">@Model.AddressLine1</div>
        </div>

        <div class="form-grid-1">
            <div class="display-label">@Html.LabelFor(model => model.AddressLine2)</div>
            <div class="display-field">@Model.AddressLine2</div>
        </div>

        <div class="form-grid-2">
            <div class="display-label">@Html.LabelFor(model => model.Postcode)</div>
            <div class="display-field">@Model.Postcode</div>
        </div>

        <div class="form-grid-1">
            <div class="display-label">@Html.LabelFor(model => model.Phone)</div>
            <div class="display-field">@Model.Phone</div>
        </div>

        <div class="form-grid-2">
            <div class="display-label">@Html.LabelFor(model => model.Mobile)</div>
            <div class="display-field">@Model.Mobile</div>
        </div>
        <br />
</fieldset>

@using (Html.BeginForm()) {
    <p>
        <input type="submit" value="Delete" /> |
        @Html.ActionLink("Back to view all", "ViewAll")
    </p>
}

'关联'类

namespace LoginFormExample.Models
{
    public partial class Associate
    {
        public int AssociateId { get; set; }

        [Required]
        [Display(Name = "First name:")]
        public string FirstName { get; set; }

        [Required]
        [Display(Name = "Last name:")]
        public string LastName { get; set; }

        [Required(ErrorMessage = "Please enter a valid email address")]
        [DataType(DataType.EmailAddress)]
        [Display(Name = "Email address:")]
        public string Email { get; set; }

        [Display(Name = "Address line 1:")]
        public string AddressLine1 { get; set; }

        [Display(Name = "Address line 2:")]
        public string AddressLine2 { get; set; }
        public int RegionId { get; set; }
        public int CityTownId { get; set; }

        [Display(Name = "Postcode:")]
        public string Postcode { get; set; }

        [Display(Name = "Phone number:")]
        public string Phone { get; set; }

        [Display(Name = "Mobile number:")]
        public string Mobile { get; set; }

有没有人知道为什么我一直收到这个错误?我已经检查了示例应用程序,我似乎无法发现任何差异。

4 个答案:

答案 0 :(得分:5)

这意味着在行

return View(db.Associates.Find(id));

dbAssociatesnull

使用Debug.Assert或断点很容易检查。在违规行上设置断点并再次运行程序,或在违规行之前插入以下代码:

Debug.Assert(db != null);
Debug.Assert(db.Associates != null);

答案 1 :(得分:2)

在您的控制器中,您没有在返回视图时设置模型...

    catch
    {
        return View();
    }

或者这找不到任何东西......

db.Associates.Find(id)

并且在您的视图中,您假设它已设置...

    @Html.HiddenFor(model => model.AssociateId)

答案 2 :(得分:0)

您的模型可能为null,因为您对db.Associates.Find(id)的调用返回null。您是否拥有表中存在的有效ID?

如果在删除帖子期间发生错误,那么将是因为您正在返回没有模型的视图。

您也在吞咽任何发生的异常。

更改

catch
{
    return View();
}

catch (Exception exception)
{
    return View();
}

并且您可以在返回View()行上放置断点并查看异常消息。

答案 3 :(得分:0)

这意味着这一行

db.Associates.Find(id)

没有找到具有该id的实体,因此返回null,因此在您的视图中您的模型为空

进一步编辑并查看堆栈跟踪:

这是抛出异常

try
        {
            using (var db = new AssociateDBEntities())
            {
                db.Entry(associate).State = System.Data.EntityState.Deleted;
                db.SaveChanges();
            }
            return RedirectToAction("ViewAll");
        }

然后这一点

catch
        {
            return View();
        }

只是吞下异常(隐藏你的真实问题)并返回一个空的删除视图,这样你的模型就是null。

删除try catch,debug,你会发现真正的问题。