1

私はASP.NETMVCを初めて使用するので、これはおそらく簡単な質問です。私はW3SchoolsMoviesチュートリアルに従い、 Naslov(私の言語では「Heading」)Sadrzaj(私の言語では「Content」)とDatum(「Date」)のフィールドを持つ小さなデータベースを作成しました。メインインデックス。これはAktuelnosti.csの現在のコードです

    namespace comp_2000.Models
{
    public class Aktuelnosti
    {
        public int ID { get; set; }
        public string Naslov { get; set; }
        public string Sadrzaj { get; set; }
        public DateTime Datum { get; set; }
    }
    public class AktuelnostiContext : DbContext
    {
        public DbSet<Aktuelnosti> Aktuelnosti { get; set; }
    }
}

これは、AktuelnostiのIndex.cshtmlに関連するビューです。

@model IEnumerable<comp_2000.Models.Aktuelnosti>

<table border="1">
    <tr>
        <th>
            @Html.DisplayNameFor(model => model.Naslov)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.Sadrzaj)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.Datum)
        </th>
        <th></th>
    </tr>


        @foreach (var item in Model) {
    <tr>
        <td width="20%">
            @Html.DisplayFor(modelItem => item.Naslov)
        </td>
        <td width="60%">
            @Html.DisplayFor(modelItem => item.Sadrzaj)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.Datum)
        </td>
        <td>
            @Html.ActionLink("Edit", "Edit", new { id=item.ID }) |
            @Html.ActionLink("Preview", "Details", new { id=item.ID }) |
            @Html.ActionLink("Delete", "Delete", new { id=item.ID })
        </td>
    </tr>

したがって、Home内のIndex.cshtmlに同じコードを試してみると、次のようになります。

@model IEnumerable<comp_2000.Models.Aktuelnosti>
@foreach (var item in Model)
{
<p>@Html.DisplayFor(modelItem => item.Naslov)</p>
<p>@Html.DisplayFor(modelItem => item.Sadrzaj)</p>
<p>@Html.DisplayFor(modelItem => item.Datum)</p>
<hr>
}

私はこれを手に入れます

 Object reference not set to an instance of an object.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. 

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

Source Error: 


Line 48:       
Line 49: 
Line 50: @foreach (var item in Model)
Line 51:     {
Line 52:     <p>@Html.DisplayFor(modelItem => item.Naslov)</p>

問題はforeachループにあると表示されます。私が間違っていることは何ですか?1つのデータベースの同じデータを2つの異なるページに表示したいだけです。

編集:ユーザーコードによって処理されなかったNullReferenceExceptionについての何かもあります。これがあなたの役に立つことを願っています。

4

1 に答える 1

1

System.NullReferenceException何かがnullであることを意味します。この場合、おそらくはModelですnull。コントローラがモデルを通過していることを確認してください。

于 2013-01-10T09:22:22.303 に答える