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

时间:2021-02-09 16:55:36

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:

我在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

1 个解决方案

#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:

假设您有一个单独的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.
}

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.

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

#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:

假设您有一个单独的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.
}

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.

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