0

I've just began learning and here I got some problem that bothered me whole day. I can't solve the following error:

[NullReferenceException: Object reference not set to an instance of an object.]

I have this code in View:

<div class="editor-field">
@Html.DropDownListFor(model => model.DogColors.ColorId, Model.Color, new { @id = "color_id" })
@Html.ValidationMessageFor(model => model.DogColors.ColorId)
</div>

And this model:

public class CreateDog
{
    public Dog Dog { get; set; }
    public DogColors DogColors { get; set; }
    public IEnumerable<SelectListItem> Colors { get; set; }
}

Controller:

public ActionResult Create()
    {
        var model = new CreateDog();
        using (var db = new ColorsRepository())
        {
            model.Colors = db.All.ToList().Select(x => new SelectListItem
            {
                Value = x.Id.ToString(),
                Text = x.Name
            });
        }
        model.Dog = new Dog();
        model.DogColors = new DogColors();
        return View(model)
    } 

I've added two colors to database and those colors are displayed in dropdown list. Problem is in this line when I click the button to submit:

@Html.DropDownListFor(model => model.DogColors.ColorId, Model.Colors, new { @id = "color_id" })

That exception is constantly thrown at that place. Any ideas what could be the problem?

Stack Trace:

[NullReferenceException: Object reference not set to an instance of an object.]
ASP._Page_Views_Projects__CreateOrEdit_cshtml.Execute() in c:\Users\Admin\Documents\Visual Studio 2012\Projects\Pro\Pro.Web\Views\Dogs\_CreateOrEdit.cshtml:65
System.Web.WebPages.WebPageBase.ExecutePageHierarchy() +197
System.Web.Mvc.WebViewPage.ExecutePageHierarchy() +97
System.Web.WebPages.WebPageBase.ExecutePageHierarchy(WebPageContext pageContext, TextWriter writer, WebPageRenderingBase startPage) +88
System.Web.Mvc.RazorView.RenderView(ViewContext viewContext, TextWriter writer, Object instance) +260
System.Web.Mvc.BuildManagerCompiledView.Render(ViewContext viewContext, TextWriter writer) +115
System.Web.Mvc.HtmlHelper.RenderPartialInternal(String partialViewName, ViewDataDictionary viewData, Object model, TextWriter writer, ViewEngineCollection viewEngineCollection) +276
System.Web.Mvc.Html.PartialExtensions.Partial(HtmlHelper htmlHelper, String partialViewName, Object model, ViewDataDictionary viewData) +108
System.Web.Mvc.Html.PartialExtensions.Partial(HtmlHelper htmlHelper, String partialViewName, Object model) +32
ASP._Page_Views_Projects_Create_cshtml.Execute() in c:\Users\Admin\Documents\Visual Studio 2012\Projects\Pro\Pro.Web\Views\Dogs\Create.cshtml:14
System.Web.WebPages.WebPageBase.ExecutePageHierarchy() +197
System.Web.Mvc.WebViewPage.ExecutePageHierarchy() +97
System.Web.WebPages.StartPage.RunPage() +17
System.Web.WebPages.StartPage.ExecutePageHierarchy() +62
System.Web.WebPages.WebPageBase.ExecutePageHierarchy(WebPageContext pageContext, TextWriter writer, WebPageRenderingBase startPage) +76
System.Web.Mvc.RazorView.RenderView(ViewContext viewContext, TextWriter writer, Object instance) +260
System.Web.Mvc.BuildManagerCompiledView.Render(ViewContext viewContext, TextWriter writer) +115
System.Web.Mvc.ViewResultBase.ExecuteResult(ControllerContext context) +295
System.Web.Mvc.ControllerActionInvoker.InvokeActionResult(ControllerContext controllerContext, ActionResult actionResult) +13
System.Web.Mvc.<>c__DisplayClass1a.<InvokeActionResultWithFilters>b__17() +23
System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilter(IResultFilter filter, ResultExecutingContext preContext, Func`1 continuation) +242
System.Web.Mvc.<>c__DisplayClass1c.<InvokeActionResultWithFilters>b__19() +21
System.Web.Mvc.ControllerActionInvoker.InvokeActionResultWithFilters(ControllerContext controllerContext, IList`1 filters, ActionResult actionResult) +177
System.Web.Mvc.Async.<>c__DisplayClass2a.<BeginInvokeAction>b__20() +89
System.Web.Mvc.Async.<>c__DisplayClass25.<BeginInvokeAction>b__22(IAsyncResult asyncResult) +102
System.Web.Mvc.Async.WrappedAsyncResult`1.End() +57
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult) +43
System.Web.Mvc.<>c__DisplayClass1d.<BeginExecuteCore>b__18(IAsyncResult asyncResult) +14
System.Web.Mvc.Async.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult ar) +23
System.Web.Mvc.Async.WrappedAsyncResult`1.End() +62
System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +57
System.Web.Mvc.Async.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult ar) +23
System.Web.Mvc.Async.WrappedAsyncResult`1.End() +62
System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) +47
System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.EndExecute(IAsyncResult asyncResult) +10
System.Web.Mvc.<>c__DisplayClass8.<BeginProcessRequest>b__3(IAsyncResult asyncResult) +25
System.Web.Mvc.Async.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult ar) +23
System.Web.Mvc.Async.WrappedAsyncResult`1.End() +62
System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +47
System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +9
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +9629296
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155
7
  • Almost all cases of NullReferenceException are the same. Please see "What is a NullReferenceException in .NET?" for some hints. Commented Mar 29, 2013 at 22:46
  • Please post the full exception stack trace if you want to be helped. Commented Mar 29, 2013 at 22:47
  • Do you have a separate Post and Get version of Create? Commented Mar 29, 2013 at 22:59
  • And, where's line 65 of CreateOrEdit.cshtml? Commented Mar 29, 2013 at 23:37
  • I have edited your title. Please see, "Should questions include “tags” in their titles?", where the consensus is "no, they should not". Commented Mar 29, 2013 at 23:37

1 Answer 1

2

Assuming you have a seperate Post version of create, When you submit your view, you are likely returning the model back without repopulating the Colors item in your model:

[HttpPost]
public ActionResult Create(CreateDog model) {
    if (ModelState.IsValid) {
        // do something
    }

    return View(model); // Colors is null at this point, because
                        // It does not get posted.  You have to repopulate it.
}

Posting only posts the selected value, it does not post the contents of the drop down list. So after the view is re-rendered, it's trying to render from a null collection reference.

Sign up to request clarification or add additional context in comments.

1 Comment

It works. Thank you! I missed that I need to do that again in Post version.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.