问题遇到的现象和发生背景
发表评论时,视图页添加用户信息的代码之后,出现未将对象设置到引用对象实例的错误,点击发表评论后下方的展示评论不会立即刷新添加刚发表的评论,但是数据库中已经插入数据
问题相关代码,请勿粘贴截图
控制器部分
[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有反应,立即刷新展示评论界面