-2

I am making an MVC 3 app which contains data about "associates", however I also need to be able to delete these "associates" through the app. I am using the Delete ActionResult but every time I try to delete an entry I get the following server error:

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

The controller:

//
// 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();
        }

'Delete' 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>
}

'Associate' class

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; }

Does anybody have any ideas as to why I keep getting this error? I have checked against example applications and I can't seem to spot any differences.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
jackie-o
  • 47
  • 1
  • 1
  • 9
  • 1
    Do you get an error when calling the delete-page, or after pressing the 'Delete' button on the delete-page (so on POST)? – Pbirkoff Feb 22 '12 at 14:24
  • I get the error when I press the 'Delete' button. – jackie-o Feb 22 '12 at 14:42
  • Then the answer of Antony Scott below probably is your solution. – Pbirkoff Feb 22 '12 at 14:49
  • possible duplicate of [What is a NullReferenceException in .NET?](http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-in-net) – John Saunders Feb 22 '12 at 15:25
  • don't forget to accept the answer which solved your problem :) – Antony Scott Feb 24 '12 at 23:35
  • I actually couldn't find a solution to this problem and so ended up deleting my database and creating a new one which seemed to solve the problem as I haven't seen the same error come up again. Thanks all for your help! – jackie-o Feb 25 '12 at 22:05

4 Answers4

5

It means that in the line

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

either db or Associates is null.

This is easy to check using Debug.Assert or a breakpoint. Set a breakpoint on the offending line and run your program again, or insert the following code before the offending line:

Debug.Assert(db != null);
Debug.Assert(db.Associates != null);
Roy Dictus
  • 32,551
  • 8
  • 60
  • 76
2

In your controller you are not setting the model when returning the view ...

    catch
    {
        return View();
    }

or this is not finding anything ...

db.Associates.Find(id)

and in your view you are assuming it is set ...

    @Html.HiddenFor(model => model.AssociateId)
Antony Scott
  • 21,690
  • 12
  • 62
  • 94
  • The delete page actually displays the details of the associate so the 'db.Associates.Find(id)' must be working, the error occurs when I hit the delete button – jackie-o Feb 22 '12 at 14:53
0

Your model is probably null because your call to db.Associates.Find(id) is returning null. Do you have a valid id that exists in the table?

If the error occurs during the Delete post, then it will be because you are returning a view without a model.

You are also swallowing any exceptions that occur.

Change

catch
{
    return View();
}

To

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

and you can place a breakpoint on the return View() line and view the exception message.

devdigital
  • 34,151
  • 9
  • 98
  • 120
  • Yes a valid entry does exist in the database table it is just having trouble removing it from the database. – jackie-o Feb 22 '12 at 14:50
  • After adding the '(Exception exception)' I received the following error message: 'Store update, insert, or delete statement affected an unexpected number of rows (0). Entities may have been modified or deleted since entities were loaded. Refresh ObjectStateManager entries.' – jackie-o Feb 22 '12 at 14:56
  • Have a look if any of these answers solve your problem - http://stackoverflow.com/questions/1836173/entity-framework-store-update-insert-or-delete-statement-affected-an-unexpec – devdigital Feb 22 '12 at 15:40
0

It means that this line

db.Associates.Find(id)

did not find an entity with that id so returned null, therefore inyour view your model is null

further to your edit and looking at the stack trace:

This is throwing an exception

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

then this bit

catch
        {
            return View();
        }

Just swallows the exception (hiding your real issue) and returns an empty delete view so your model is null.

Remove the try catch, debug and you will find your real problem.

Ben Robinson
  • 21,601
  • 5
  • 62
  • 79
  • The delete page actually displays the details of the associate so the 'db.Associates.Find(id)' must be working, the error occurs when I hit the delete button. – jackie-o Feb 22 '12 at 14:52
  • Thanks Ben, now ' I get the following error message: 'Store update, insert, or delete statement affected an unexpected number of rows (0). Entities may have been modified or deleted since entities were loaded. Refresh ObjectStateManager entries.' Just need to figure out how to solve this now :s – jackie-o Feb 22 '12 at 16:09
  • Check the primary key value of your associate entity in your delete statement, the error means you are trying to delete something that does not exist in the database – Ben Robinson Feb 22 '12 at 16:12