尝试在我的网页上添加评论系统。我希望能够为每个页面上的注释构建一个列表视图。
我想我可以使用脚手架代码并将其返回到部分视图,方法是将返回值更改为PartialView(db.Comments.ToList());
,将ViewResult
更改为ActionResult
。
它在@for (item in model) {....}
处以空引用exception error
中断。
那么......关于我怎么做的任何想法? EX:任何评论系统。
@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; }
}
}