1. ホーム
  2. c#

[解決済み] MVCエラー。オブジェクト参照がオブジェクトのインスタンスに設定されていない

2022-02-28 02:56:35

質問

今日のためにこのmvcアプリをあきらめかけている!?

Mvc Music Store Tutorialに従っているのですが、54ページで行き詰まっています。

このようなエラーが発生します。

System.NullReferenceException: オブジェクト のインスタンスに設定されていない オブジェクトを使用します。

以下のコードの3段落目のブロック(dropdownlist)でエラーが発生します。

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

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

MvcMovies1 と呼んでいたことに改めて気づきました。これはタイプミスですが、すべて適切にマークアップされています。

解決方法は?

はたして Album があります。 ArtistId を呼び出しているので、その行では Model.ArtistId で、もし Album がそのプロパティを持っていない場合、ヌル参照例外が発生します。これは、モデルがビューに強くタイプされたオブジェクトの略記であり、それがたまたま Album この場合

上記のコードでは、ViewData["Artists"]を設定している箇所がありません。それがあなたの問題である可能性もあるので、どこかにそれを設定していますか?

EDIT

アクションに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);
 }