发表评论时,视图页添加用户信息的代码之后,出现未将对象设置到引用对象实例的错误,点击发表评论后下方的展示评论不会立即刷新添加刚发表的评论,但是数据库中已经插入数据
控制器部分
[HttpPost]
[ValidateAntiForgeryToken]
[ValidateInput(false)]
[IsLogin(IsCheck = false)]
public ActionResult AddpostpicComment(string postid, string comment)
{
if (Session["login"] != null)
{
Comment c = new Comment();
string id;
Random rnd = new Random();
int rndNum = rnd.Next(10000000, 99999999);
id = "M0" + DateTime.Now.ToString("yyyy-MM-dd")+ rndNum.ToString();
c.plcommentId = id;
c.plcommentContent = comment;
c.postId = postid;
c.commentTime = DateTime.Now;
c.delTime = null;
c.Is_Del = false;
c.userId = ((UserInfo)Session["login"]).userId;
c.lastCommentid = null;
db.Comments.Add(c);
if (db.SaveChanges() > 0)
{
var comm = db.Comments.Where(t => t.postId== postid).OrderByDescending(t => t.commentTime);
return PartialView("PostpicComment", comm);
}
else
{
return Content("Fault");
}
}
else
{
return Content("Login");
}
发表评论视图主要代码
<div id="L">
<div id="pinglun">
@using (Ajax.BeginForm("AddpostpicComment", "posts", new AjaxOptions
{
HttpMethod = "post",
UpdateTargetId = "result",
OnSuccess = "Comment"
}))
{@Html.AntiForgeryToken()
@Html.ValidationSummary(true)
<input type="hidden" name="postId" id="" value="@Model.postId" />
<textarea name="comment" id="editor"></textarea>
<script>
var editor = CKEDITOR.replace('editor');
</script>
<br />
<input type="submit" value="发表评论" />
}
</div>
<div id="result" style="color:black;">
@Html.Action("PostpicComment", "posts", new { id = Model.postId })
@*@{Html.RenderPartial("PostpicComment", ViewBag.Comment as IEnumerable<WebWEI.Models.Comment>);}*@
</div>
</div>
展示评论视图
@model IEnumerable<WebWEI.Models.Comment>
@{
Layout = null;
}
<h3>图片帖评论(@Model.Count())</h3>
<div>
@foreach (var item in Model)
{
<hr />
<div id="head">
<a href="@Url.Action("PersonalCenter","User",new { id = item.userId})">
<img src="@item.UserInfo.userHeadPortrait" style="border-radius:50%;">
</a>
</div>
<div>
<p>@Html.Raw(item.plcommentContent)</p>
</div>
}
</div>
删除下面展示用户头像信息的代码就不会报错
<div id="head">
<a href="@Url.Action("PersonalCenter","User",new { id = item.userId})">
<img src="@item.UserInfo.userHeadPortrait" style="border-radius:50%;">
</a>
</div>
显示发评论用户信息,点击发表评论后,ajax有反应,立即刷新展示评论界面
说明其中有个一条记录的UserInfo属性为null
var comm = db.Comments.Where(t => t.postId== postid).OrderByDescending(t => t.commentTime);
这里只是读取评论的信息,没有看到读取用户信息的代码,是设置了关系级联读取?如果是那么发布评论用户的信息应该被删掉了导致没有读取出用户的信息,但是评论信息存在的导致userinfo为null。
改下面可以保证代码正常执行,但是头像不会显示
<div id="head">
<a href="@Url.Action("PersonalCenter","User",new { id = item.userId})">
@if(item.UserInfo!=null){
<img src="@item.UserInfo.userHeadPortrait" style="border-radius:50%;">
}
</a>
</div>