user2675973
user2675973

Reputation: 227

MVC NullReferenceException Error with Standard Scaffolding

I have a NullReferenceException Error in my little MVC 5 Application. I read the posts on it but I still don’t see the mistake that I made. Create throws an NullReferenceException exception and was scaffoled out automatically.

    public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute(
               name: "OutreachOverview",
               url: "{controller}/{action}/{id}",
               defaults: new { controller = "Outreaches", action = "Index", id = UrlParameter.Optional }
               );

            routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
            );
   }

namespace WebApplication9.Models
{
    public class Outreach
    {
        [Key]        
        public string TargetContact { get; set; }
        public string NextOutreachStep { get; set; }
        public string GoalOfOutreach { get; set; }
        public string Currency { get; set; }
        public string TalkingPoints { get; set; }
        public DateTime DueDate { get; set; }
        public string PriorOutreach { get; set; }
        public bool Done { get; set; }
        public string FollowUp { get; set; }
} }

public class NetworkingContext : DbContext
    {
        public NetworkingContext() : base("NetworkingAppConnString")
        {
            Database.SetInitializer(new MigrateDatabaseToLatestVersion<NetworkingContext,
                WebApplication9.Migrations.Configuration>("NetworkingAppConnString"));
        }
        public DbSet<Outreach> Outreach { get; set; }
        public DbSet<Diagnostics> Diagnostics { get; set; }


        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);
        }


    }

I left some of the code out that deal with the other properties. It just repeats itself.

@model WebApplication9.Models.Outreach

@{
    ViewBag.Title = "Create";
}

<h2>Create</h2>

@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()

    <div class="form-horizontal">
        <h4>Outreach</h4>
        <hr />
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        <div class="form-group">
            @Html.LabelFor(model => model.TargetContact, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.TargetContact, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.TargetContact, "" , new { @class = "text-danger" })
            </div>
        </div>

                <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Create" class="btn btn-default" />
            </div>
        </div>
    </div>
}

<div>
    @Html.ActionLink("Back to List", "Index")
</div>

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}

The Controller:

// GET: Outreaches/Create
        public ActionResult Create()
        {
            return View();
        }

        // POST: Outreaches/Create
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create([Bind(Include = "TargetContact,NextOutreachStep,GoalOfOutreach,Currency,TalkingPoints,DueDate,PriorOutreach,Done,FollowUp")] Outreach outreach)
        {
            var test = string.Empty;
            if (ModelState.IsValid)
            {
                db.Outreach.Add(outreach);
                db.SaveChanges();
                return RedirectToAction("Index");
            }

            return View(outreach);
        }

The Complete Exception This Der Objektverweis wurde nicht auf eine Objektinstanz festgelegt translated into english means Object reference not set to an instance of an object

[NullReferenceException: Der Objektverweis wurde nicht auf eine Objektinstanz festgelegt.]
   System.Web.Mvc.<ConvertResults>d__2.MoveNext() +56
   System.Web.Mvc.<Validate>d__1.MoveNext() +562
   System.Web.Mvc.DefaultModelBinder.OnModelUpdated(ControllerContext controllerContext, ModelBindingContext bindingContext) +120
   System.Web.Mvc.DefaultModelBinder.BindComplexElementalModel(ControllerContext controllerContext, ModelBindingContext bindingContext, Object model) +68
   System.Web.Mvc.DefaultModelBinder.BindComplexModel(ControllerContext controllerContext, ModelBindingContext bindingContext) +1197
   System.Web.Mvc.DefaultModelBinder.BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) +330
   System.Web.Mvc.ControllerActionInvoker.GetParameterValue(ControllerContext controllerContext, ParameterDescriptor parameterDescriptor) +338
   System.Web.Mvc.ControllerActionInvoker.GetParameterValues(ControllerContext controllerContext, ActionDescriptor actionDescriptor) +105
   System.Web.Mvc.Async.<>c__DisplayClass21.<BeginInvokeAction>b__19(AsyncCallback asyncCallback, Object asyncState) +743
   System.Web.Mvc.Async.WrappedAsyncResult`1.CallBeginDelegate(AsyncCallback callback, Object callbackState) +14
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +128
   System.Web.Mvc.Async.AsyncControllerActionInvoker.BeginInvokeAction(ControllerContext controllerContext, String actionName, AsyncCallback callback, Object state) +343
   System.Web.Mvc.Controller.<BeginExecuteCore>b__1c(AsyncCallback asyncCallback, Object asyncState, ExecuteCoreState innerState) +25
   System.Web.Mvc.Async.WrappedAsyncVoid`1.CallBeginDelegate(AsyncCallback callback, Object callbackState) +30
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +128
   System.Web.Mvc.Controller.BeginExecuteCore(AsyncCallback callback, Object state) +465
   System.Web.Mvc.Controller.<BeginExecute>b__14(AsyncCallback asyncCallback, Object callbackState, Controller controller) +18
   System.Web.Mvc.Async.WrappedAsyncVoid`1.CallBeginDelegate(AsyncCallback callback, Object callbackState) +20
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +128
   System.Web.Mvc.Controller.BeginExecute(RequestContext requestContext, AsyncCallback callback, Object state) +374
   System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.BeginExecute(RequestContext requestContext, AsyncCallback callback, Object state) +16
   System.Web.Mvc.MvcHandler.<BeginProcessRequest>b__4(AsyncCallback asyncCallback, Object asyncState, ProcessRequestState innerState) +52
   System.Web.Mvc.Async.WrappedAsyncVoid`1.CallBeginDelegate(AsyncCallback callback, Object callbackState) +30
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +128
   System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContextBase httpContext, AsyncCallback callback, Object state) +384
   System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContext httpContext, AsyncCallback callback, Object state) +48
   System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.BeginProcessRequest(HttpContext context, AsyncCallback cb, Object extraData) +16
   System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +103
   System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155

Upvotes: 0

Views: 871

Answers (1)

kd345205
kd345205

Reputation: 319

Just had this same issue, thought I'd share my solution. In my case my object implemented IValidatableObject and in my validate method I returned null. Changing that fixed my Issue. Until then the breakpoint on the "POST" action result was never hit, exactly as you described. Even the first several lines of my exception are identical to yours.

Looking at your situation, it looks like you have a string key. Any chance your model is not liking that or are you doing any validation like I was?

Upvotes: 4

Related Questions