MVC错误:未将对象引用设置为对象的实例

时间:2021-03-21 16:55:09

I'm close to giving up on this mvc app for today!!

今天我已经接近放弃这个mvc应用了!!

I'm following the Mvc Music Store Tutorial and I'm stuck on page 54.

我正在关注Mvc音乐商店教程,我被困在第54页。

this is the error I'm getting:

这是我得到的错误:

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

System.NullReferenceException:未将对象引用设置为对象的实例。

The error occurs in the third paragraph block (dropdownlist) in the following code:

错误发生在以下代码中的第三个段落(下拉列表)中:

<%@ Import Namespace ="MvcMovies1" %>
<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<MvcMovies1.Models.Album>" %>

<p>
    <%: Html.LabelFor(model => model.Title) %>
    <%: Html.TextAreaFor(model => model.Title) %>
    <%: Html.ValidationMessageFor(model => model.Title) %>
</p>

<p>
    <%: Html.LabelFor(model => model.Price) %>
    <%: Html.TextAreaFor(model => model.Price) %>
    <%: Html.ValidationMessageFor(model => model.Price) %>
</p>

<p>
    <%: Html.LabelFor(model => model.AlbumArtUrl) %>
    <%: Html.TextAreaFor(model => model.AlbumArtUrl) %>
    <%: Html.ValidationMessageFor(model => model.AlbumArtUrl) %>
</p>

<p>
    <%: Html.LabelFor(model => model.Artist) %>
    <%: Html.DropDownList("ArtistId", new SelectList(ViewData["Artists"] as IEnumerable, "ArtistId", "Name", Model.ArtistId)) %>
</p>

<p>
    <%: Html.LabelFor(model => model.Genre) %>
    <%: Html.DropDownList("GenreId", new SelectList(ViewData["Genres"] as IEnumerable, "GenreId", "Name", Model.GenreId)) %>
</p>

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

This ascx file is contained within an Edit.aspx file:

此ascx文件包含在Edit.aspx文件中:

<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<MvcMovies1.ViewModels.StoreManagerViewModel>" %>
<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
    Edit
</asp:Content>

<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<form id="form1" runat="server">
    <h2>Edit</h2>
    <% using (Html.BeginForm())
       { %>
      <%: Html.ValidationSummary(true)%>

    <fieldset>
      <legend>Edit Album</legend>
      <%: Html.EditorFor(model => model.Album,
          new { Artists = Model.Artists, Genres = Model.Genres }) %>

          <p><input type="submit" value="Save" /></p>


    </fieldset>

      <% } %>
      </form>
</asp:Content>

I realise there's a lot of code there but if anyone can see something obvious that I am doing wrong I'd be very grateful.

我意识到那里有很多代码,但是如果有人能够看到一些明显我做错的话,我会非常感激。

EDIT

StoreManagerController.cs (Edit)

 public ActionResult Edit(int id)
    {
        var viewModel = new StoreManagerViewModel
        {
            Album = storeDB.Albums.SingleOrDefault(a => a.AlbumId == id),
            Genres = storeDB.Genres.ToList(),
            Artists = storeDB.Artists.ToList()
        };

        return View(viewModel);
    }

Andddd..StoreManagerViewModel.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using MvcMovies1.Models;

namespace MvcMovies1.ViewModels
{
    public class StoreManagerViewModel
    {
        public Album Album { get; set; }
        public List<Artist> Artists { get; set; }
        public List<Genre> Genres { get; set; }
    }
}

Again I realise i called it MvcMovies1, this was a typo but everything is marked up accordingly.

我再次意识到我称之为MvcMovies1,这是一个错字,但所有内容都相应标记。

6 个解决方案

#1


6  

Does Album have an ArtistId since in that line you are calling Model.ArtistId and if Album doesn't have that property on it you will get a null reference exception. That's because the Model is a shorthand for the object that is strongly typed to your view, which happens to be Album in your case.

相册是否具有ArtistId,因为在该行中您调用的是Model.ArtistId,如果相册上没有该属性,您将获得空引用异常。这是因为模型是对您的视图强类型的对象的简写,在您的情况下恰好是Album。

There is no where in your above code where you are setting the ViewData["Artists"]. Are you setting that anywhere since that could be your issue too.

您在上面的代码中没有设置ViewData [“Artists”]的位置。您是否在任何地方设置,因为这也可能是您的问题。

EDIT

Set the ViewData in the action and it should work:

在操作中设置ViewData,它应该工作:

public ActionResult Edit(int id)
{
     var viewModel = new StoreManagerViewModel
     {
         Album = storeDB.Albums.SingleOrDefault(a => a.AlbumId == id),
         Genres = storeDB.Genres.ToList(),
         Artists = storeDB.Artists.ToList()
     };

     ViewData["Artists"] = storeDB.Artists.ToList();
     ViewData["Genres"] = storeDB.Genres.ToList();

     return View(viewModel);
 }

#2


6  

First you need to add properties in your view model to hold selected artist and selected genre:

首先,您需要在视图模型中添加属性以保存选定的艺术家和所选类型:

public class StoreManagerViewModel
{
    public Album Album { get; set; }
    public int? SelectedArtistId { get; set; }
    public List<Artist> Artists { get; set; }
    public int? SelectedGenreId { get; set; }
    public List<Genre> Genres { get; set; }
}

Then in your Edit.aspx view instead of:

然后在Edit.aspx视图中而不是:

<%: Html.EditorFor(model => model.Album,
    new { Artists = Model.Artists, Genres = Model.Genres }) %>

You could simply:

你可以简单地说:

<%: Html.EditorForModel() %>

and in your editor template ~/Views/Home/EditorTemplates/Album.ascx:

并在您的编辑器模板中〜/ Views / Home / EditorTemplates / Album.ascx:

<%@ Import Namespace ="MvcMovies1" %>
<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<MvcMovies1.Models.Album>" %>

<p>
    <%: Html.LabelFor(model => model.Title) %>
    <%: Html.TextAreaFor(model => model.Title) %>
    <%: Html.ValidationMessageFor(model => model.Title) %>
</p>

<p>
    <%: Html.LabelFor(model => model.Price) %>
    <%: Html.TextAreaFor(model => model.Price) %>
    <%: Html.ValidationMessageFor(model => model.Price) %>
</p>

<p>
    <%: Html.LabelFor(model => model.AlbumArtUrl) %>
    <%: Html.TextAreaFor(model => model.AlbumArtUrl) %>
    <%: Html.ValidationMessageFor(model => model.AlbumArtUrl) %>
</p>

and in your editor template ~/Views/Home/EditorTemplates/StoreManagerViewModel:

并在您的编辑器模板中〜/ Views / Home / EditorTemplates / StoreManagerViewModel:

<%@ Import Namespace ="MvcMovies1" %>
<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<MvcMovies1.ViewModels.StoreManagerViewModel>" %>

<%: Html.EditorFor(model => model.Album) %>

<p>
    <%: Html.LabelFor(model => model.SelectedArtistId) %>
    <%: Html.DropDownListFor(model => model.SelectedArtistId, new SelectList(Model.Artists, "ArtistId", "Name")) %>
</p>

<p>
    <%: Html.LabelFor(model => model.SelectedGenreId) %>
    <%: Html.DropDownListFor(model => model.SelectedGenreId, new SelectList(Model.Genres, "GenreId", "Name")) %>
</p>

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

#3


1  

Have you tried casting to List and List instead of IEnumerable?

您是否尝试过转换为List和List而不是IEnumerable?

#4


1  

u r simply not setting ViewData["Artists"] and ViewData["genres"] as I can see from your action method.

你根本没有设置ViewData [“Artists”]和ViewData [“genres”],就像我从你的动作方法中看到的那样。

Make sure, you are setting these values somewhere during lifetime of a request if u want to use them in ur view

如果你想在你的视图中使用它们,请确保在请求的生命周期中将这些值设置在某处

#5


0  

Had the same error while trying to run migration (update-database). had 2 projects namely ViewProject and DBcontextProject.

尝试运行迁移时出现相同的错误(update-database)。有2个项目,即ViewProject和DBcontextProject。

my problem was that I made ViewProject a start-up project and ran migration on DBcontextProject.

我的问题是我使ViewProject成为一个启动项目并在DBcontextProject上运行迁移。

The solution was to make DBcontextProject a start-up project and run migration on DBcontextProject.

解决方案是使DBcontextProject成为一个启动项目并在DBcontextProject上运行迁移。

#6


0  

problem:

Object reference not set to an instance of an object

你调用的对象是空的

Solution:

pubblic ActionResult yourDetails()
{
     List<YourEntityName> PropertyName= new List<YourEntityName>();
     list = db.PropertyName.ToList();
     return View(list);
}

YourEntityName Mean your Table Name i.e PassengerDetial

YourEntityName表示您的表名,即PassengerDetial

PropertyName Mean your Class pubblic property i.e PassengerDetails

PropertyName表示您的Class pubblic属性,即PassengerDetails

pubblic Class PassengerDetailContext : DbContext 
{
  pubblic DbSet<PassengerDetail>  passegerDetails {get;set;}
}

List<PassengerDetail> passegerDetails = new List<PassengerDetail>();
list = db.passegerDetails.ToList();
return View(list);

#1


6  

Does Album have an ArtistId since in that line you are calling Model.ArtistId and if Album doesn't have that property on it you will get a null reference exception. That's because the Model is a shorthand for the object that is strongly typed to your view, which happens to be Album in your case.

相册是否具有ArtistId,因为在该行中您调用的是Model.ArtistId,如果相册上没有该属性,您将获得空引用异常。这是因为模型是对您的视图强类型的对象的简写,在您的情况下恰好是Album。

There is no where in your above code where you are setting the ViewData["Artists"]. Are you setting that anywhere since that could be your issue too.

您在上面的代码中没有设置ViewData [“Artists”]的位置。您是否在任何地方设置,因为这也可能是您的问题。

EDIT

Set the ViewData in the action and it should work:

在操作中设置ViewData,它应该工作:

public ActionResult Edit(int id)
{
     var viewModel = new StoreManagerViewModel
     {
         Album = storeDB.Albums.SingleOrDefault(a => a.AlbumId == id),
         Genres = storeDB.Genres.ToList(),
         Artists = storeDB.Artists.ToList()
     };

     ViewData["Artists"] = storeDB.Artists.ToList();
     ViewData["Genres"] = storeDB.Genres.ToList();

     return View(viewModel);
 }

#2


6  

First you need to add properties in your view model to hold selected artist and selected genre:

首先,您需要在视图模型中添加属性以保存选定的艺术家和所选类型:

public class StoreManagerViewModel
{
    public Album Album { get; set; }
    public int? SelectedArtistId { get; set; }
    public List<Artist> Artists { get; set; }
    public int? SelectedGenreId { get; set; }
    public List<Genre> Genres { get; set; }
}

Then in your Edit.aspx view instead of:

然后在Edit.aspx视图中而不是:

<%: Html.EditorFor(model => model.Album,
    new { Artists = Model.Artists, Genres = Model.Genres }) %>

You could simply:

你可以简单地说:

<%: Html.EditorForModel() %>

and in your editor template ~/Views/Home/EditorTemplates/Album.ascx:

并在您的编辑器模板中〜/ Views / Home / EditorTemplates / Album.ascx:

<%@ Import Namespace ="MvcMovies1" %>
<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<MvcMovies1.Models.Album>" %>

<p>
    <%: Html.LabelFor(model => model.Title) %>
    <%: Html.TextAreaFor(model => model.Title) %>
    <%: Html.ValidationMessageFor(model => model.Title) %>
</p>

<p>
    <%: Html.LabelFor(model => model.Price) %>
    <%: Html.TextAreaFor(model => model.Price) %>
    <%: Html.ValidationMessageFor(model => model.Price) %>
</p>

<p>
    <%: Html.LabelFor(model => model.AlbumArtUrl) %>
    <%: Html.TextAreaFor(model => model.AlbumArtUrl) %>
    <%: Html.ValidationMessageFor(model => model.AlbumArtUrl) %>
</p>

and in your editor template ~/Views/Home/EditorTemplates/StoreManagerViewModel:

并在您的编辑器模板中〜/ Views / Home / EditorTemplates / StoreManagerViewModel:

<%@ Import Namespace ="MvcMovies1" %>
<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<MvcMovies1.ViewModels.StoreManagerViewModel>" %>

<%: Html.EditorFor(model => model.Album) %>

<p>
    <%: Html.LabelFor(model => model.SelectedArtistId) %>
    <%: Html.DropDownListFor(model => model.SelectedArtistId, new SelectList(Model.Artists, "ArtistId", "Name")) %>
</p>

<p>
    <%: Html.LabelFor(model => model.SelectedGenreId) %>
    <%: Html.DropDownListFor(model => model.SelectedGenreId, new SelectList(Model.Genres, "GenreId", "Name")) %>
</p>

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

#3


1  

Have you tried casting to List and List instead of IEnumerable?

您是否尝试过转换为List和List而不是IEnumerable?

#4


1  

u r simply not setting ViewData["Artists"] and ViewData["genres"] as I can see from your action method.

你根本没有设置ViewData [“Artists”]和ViewData [“genres”],就像我从你的动作方法中看到的那样。

Make sure, you are setting these values somewhere during lifetime of a request if u want to use them in ur view

如果你想在你的视图中使用它们,请确保在请求的生命周期中将这些值设置在某处

#5


0  

Had the same error while trying to run migration (update-database). had 2 projects namely ViewProject and DBcontextProject.

尝试运行迁移时出现相同的错误(update-database)。有2个项目,即ViewProject和DBcontextProject。

my problem was that I made ViewProject a start-up project and ran migration on DBcontextProject.

我的问题是我使ViewProject成为一个启动项目并在DBcontextProject上运行迁移。

The solution was to make DBcontextProject a start-up project and run migration on DBcontextProject.

解决方案是使DBcontextProject成为一个启动项目并在DBcontextProject上运行迁移。

#6


0  

problem:

Object reference not set to an instance of an object

你调用的对象是空的

Solution:

pubblic ActionResult yourDetails()
{
     List<YourEntityName> PropertyName= new List<YourEntityName>();
     list = db.PropertyName.ToList();
     return View(list);
}

YourEntityName Mean your Table Name i.e PassengerDetial

YourEntityName表示您的表名,即PassengerDetial

PropertyName Mean your Class pubblic property i.e PassengerDetails

PropertyName表示您的Class pubblic属性,即PassengerDetails

pubblic Class PassengerDetailContext : DbContext 
{
  pubblic DbSet<PassengerDetail>  passegerDetails {get;set;}
}

List<PassengerDetail> passegerDetails = new List<PassengerDetail>();
list = db.passegerDetails.ToList();
return View(list);