对象引用未设置为对象的实例(下拉列表)

时间:2013-03-29 22:45:26

标签: asp.net linq entity-framework asp.net-mvc-4 nullreferenceexception

我刚刚开始学习,在这里我遇到了一整天困扰我的问题。我无法解决以下错误:

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

我在View中有这段代码:

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

这个模型:

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

控制器:

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

我为数据库添加了两种颜色,这些颜色显示在下拉列表中。当我点击按钮提交时,问题出在这一行:

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

那个地方经常被抛出异常。任何想法可能是什么问题?

堆栈追踪:

[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

1 个答案:

答案 0 :(得分:2)

假设您有一个单独的Post版本的创建,当您提交视图时,您可能会返回模型而无需重新填充模型中的Colors项目:

[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.
}

过帐仅发布所选值,不会发布下拉列表的内容。因此,在重新渲染视图之后,它正在尝试从空集合引用中进行渲染。