业务需求是要做一个论坛的只看楼主功能。
逻辑很简单,前台传参到后台获取评论的list然后遍历显示即可。
搜寻资料我尝试了两种方式:
1、从后台获取json然后在前台赋值
2、从后台回去界面显示在前台
第一种方式成功了一半,能获取到正确的json但是无法在前台的回调里给@里的变量赋值,只能拼接html显示,这样对于简单的html还好,但是复杂的div就很难受。
实体类:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
public class Reply
{
public int reply_id { get; set; }
public int post_id { get; set; }
public int user_id { get; set; }
public string reply_time { get; set; }
public string reply_context { get; set; }
public string avater { get; set; }
public string user_name { get; set; }
public int user_point { get; set; }
}
前端:
@{
ViewBag.Title = "PostDetail";
User loginUser = (User)Session["User"];
if (loginUser == null)
{
loginUser = new User();
loginUser.uId = 0;
}
Post nowPost = (Post)ViewData["nowPost"];
User postOwner = (User)ViewData["postOwner"];
List<Post> userPostList = (List<Post>)ViewData["userPostList"];
List<Goods> postGoods = (List<Goods>)ViewData["postGoods"];
List<Reply> postReplyList = (List<Reply>)ViewData["postReplyList"];
}
<input type="button" value="只看楼主" id="ajaxFloor" name="ajaxFloor" />
<div id="Jfloorlist"></div>
<script type="text/javascript" language="javascript">
$(document).ready(function () {
$("#ajaxFloor").click(function () {
$.ajax({
type: "POST",
url: "/Reply/ReadLandlord",
data: "user_id=@nowPost.user_id&post_id=@nowPost.post_id",
dataType: "json",
success: function (response) {
//console.log(response);
var replyList = JSON.parse(response);
//console.log(replyList);
var landlordReply = "";
for (var i = 0; i < replyList.length ; i++) {
landlordReply +=
"<tr>" +
"<td>" + replyList[i].user_name + "</td>" +
"<td>" + replyList[i].reply_time + "</td>" +
"<td>" + replyList[i].reply_context + "</td>" +
"</tr>"
}
$("#Jfloorlist").html(landlordReply);
}
});
});
});
</script>
后端:
//拿到楼主评论json配合ajax
[HttpPost]
public JsonResult ReadLandlord(int user_id, int post_id)
{
List<Reply> replyList = replyService.getReplyListByUID(user_id, post_id);
string result = JsonConvert.SerializeObject(replyList);
return Json(result);
}
第二种方法达到了预期。
实体类:如上
前端:@变量如上
<input type="button" value="只看楼主" id="ajaxFloor" name="ajaxFloor" />
<div id="Jfloorlist"></div>
<script type="text/javascript" language="javascript">
$(document).ready(function () {
$("#ajaxFloor").click(function () {
$('#Jfloorlist').load("@Url.Action("ReadLandlord", "Reply")?user_id=@nowPost.user_id&post_id=@nowPost.post_id")
});
});
</script>
后端:
/// <summary>
/// 只看楼主评论
/// </summary>
/// <param name="user_id"></param>
/// <param name="post_id"></param>
/// <returns></returns>
public ActionResult ReadLandlord(int user_id, int post_id)
{
if (Request.IsAjaxRequest())
{
return PartialView(replyService.getReplyListByUID(user_id, post_id));
}
return View(replyService.getReplyListByUID(user_id, post_id));
}