0

试图将评论系统添加到我的页面。我希望能够为每个页面上的评论搭建一个列表视图。

我想我可以只使用脚手架代码并通过将返回值更改为 a 并将其放入部分视图PartialView(db.Comments.ToList());中。ViewResultActionResult

@for (item in model) {....}它以空引用中断exception error

所以......关于我如何做到这一点的任何想法?例如:任何地方的任何评论系统。

    @model IEnumerable<_2nditeration.Models.Comment>

@{
    ViewBag.Title = "Messages";
}

<h2>Messages</h2>

<p>
    @Html.ActionLink("Create New", "Create")
</p>
<table>
    <tr>
        <th>
            uname
        </th>
        <th>
            email
        </th>
        <th>
            subject
        </th>
        <th>
            referrer
        </th>
        <th>
            Created
        </th>
        <th>
            comment
        </th>
        <th></th>
    </tr>
@*BREAKS HERE!!!!!!with a null reference exception on the Model object*@
@foreach (var item in Model) {
    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.uname)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.email)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.subject)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.referrer)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.Created)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.comment)
        </td>
        <td>
            @Html.ActionLink("Edit", "Edit", new { id=item.ID }) |
            @Html.ActionLink("Details", "Details", new { id=item.ID }) |
            @Html.ActionLink("Delete", "Delete", new { id=item.ID })
        </td>
    </tr>
}

</table>

控制器动作

public class CommentsController : Controller
{
    private DbEntity db = new DbEntity();

    //
    // GET: /Comments/Read
    public ActionResult ReadComments()
    {
        return PartialView(db.Comments.ToList());
    }

和模型

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;

namespace _2nditeration.Models
{
    public class Comment
    {
        public int ID { get; set; }
        [Display ( Name = "Name")]
        public string uname { get; set; }
        [Display(Name = "Email Address")]
        public string email { get; set; }
        [Display(Name = "Subject")]
        public string subject { get; set; }
        public string referrer { get; set; }
        public DateTime? Created { set; get; }
        [Required]
        [Display(Name = "Comment")]
        public string comment { get; set; }
    }
}
4

0 回答 0