English 中文(简体)
MVC错误:对象引用未设置为对象的实例
原标题:MVC Error: Object reference not set to an instance of an object

今天我几乎要放弃这个mvc应用了!!

我正在学习Mvc音乐商店教程,我一直停留在第54页。

这是我得到的错误:

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

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

<%@ 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>

此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>

我意识到那里有很多代码,但如果有人能看到我做错了什么,我会非常感激。

编辑

StoreManagerController.cs(编辑)

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

和。。StoreManager视图模型.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; }
    }
}

我再次意识到我称之为MvcMovies1,这是一个拼写错误,但一切都有相应的标记。

最佳回答

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

上面的代码中没有设置ViewData[“Artists”]的位置。你把它放在哪里了吗?因为这也可能是你的问题。

编辑

在操作中设置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);
 }
问题回答

首先,您需要在视图模型中添加属性,以容纳选定的艺术家和选定的流派:

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

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

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

您可以简单地:

<%: Html.EditorForModel() %>

以及在编辑器模板~/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>

并且在编辑器模板~/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>

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

问题:

对象引用未设置为对象的实例

解决方案:

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

YourEntityName表示您的表名,即PassengerDetial

PropertyName表示您的类公共属性,即PassengerDetails

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

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

正如我从你的动作方法中看到的那样,你只是没有设置ViewData[“Artists”]ViewData[“types”]

若要在视图中使用这些值,请确保在请求的生存期内的某个位置设置了这些值。

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

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

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





相关问题
Anyone feel like passing it forward?

I m the only developer in my company, and am getting along well as an autodidact, but I know I m missing out on the education one gets from working with and having code reviewed by more senior devs. ...

NSArray s, Primitive types and Boxing Oh My!

I m pretty new to the Objective-C world and I have a long history with .net/C# so naturally I m inclined to use my C# wits. Now here s the question: I feel really inclined to create some type of ...

C# Marshal / Pinvoke CBitmap?

I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class. My import looks like this: [DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ...

How to Use Ghostscript DLL to convert PDF to PDF/A

How to user GhostScript DLL to convert PDF to PDF/A. I know I kind of have to call the exported function of gsdll32.dll whose name is gsapi_init_with_args, but how do i pass the right arguments? BTW, ...

Linqy no matchy

Maybe it s something I m doing wrong. I m just learning Linq because I m bored. And so far so good. I made a little program and it basically just outputs all matches (foreach) into a label control. ...

热门标签