[英]How to send partial view to ajax in mvc4
我有一个ajax调用功能。 在其中,我称局部视图。 该视图用于显示评论。 如何使用Ajax刷新此视图? 我在上下文中不喜欢json,因为我的linq查询是使用模型设置的。 因此,这些具有部分视图的模型应该发送给ajax方法。 Ajax方法应该替换我的div。 请注意,在ajax调用之前,应在页面加载时首先呈现此视图。 我不明白这一点。 我怎么了
$.ajax({
url: '/Home/Item',
type: 'POST',
data: { itemid: itemid },
success: function (data) {
$('.mycontainer').html(data);
}
});
控制者
public ActionResult Item(int itemid)
{
FoodContext db = new FoodContext();
ViewBag.FoodItems = db.FoodItems.Where(row => row.itemid == itemid);
List<ImageComment> comments = (from user in db.TxtComments
join o in db.Logins on user.username equals o.username
where user.itemid == itemid
select new ImageComment
{
ImageUrl = o.imgurl,
Comment = user.txtcmt,
ImgCmntUrl = user.imgurl,
Cmntdate = user.cmtdate,
Username = user.username,
}).OrderByDescending(x => x.Cmntdate).ToList();
ViewModel vm = new ViewModel { ImageComments = comments };
return PartialView("_Comments", vm);
}
部分视图
@model ViewModel
@foreach (ImageComment comment in Model.ImageComments)
{
<table width="100%" height="152" border="0">
<tr>
<td width="101" rowspan="2" valign="top"><img src="@comment.ImageUrl" width="100%" height="100%" /></td>
<td height="27" colspan="3" valign="middle"><p> @comment.Username Commented On On @comment.Cmntdate</p></td>
</tr>
<tr>
<td colspan="2" rowspan="2"><div style="width:70%;">
@if (@comment.ImgCmntUrl != null)
{
<img src="@Url.Content(comment.ImgCmntUrl)" width="100%" height="100%" />
}
</div>
<div style="background-color:#E3EEFA;width:68%;min-height:50px;padding:5px;">@comment.Comment</div></td>
<td width="209" height="29"> </td>
</tr>
<tr>
<td> </td>
<td> </td>
</tr>
<tr>
<td height="23"> </td>
<td>Like this.</td>
<td>Unlike this</td>
<td> </td>
</tr>
<tr>
<td height="23"> </td>
<td width="303"> </td>
<td width="588"> </td>
<td> </td>
</tr>
</table>
}
我的观点
<div class="mycontainer">
</div>
您可以使用jquery加载功能:
<div class=".mycontainer"></div>
<script>
function ReloadComments(){
$(".mycontainer").load("@Url.Action("Item", new { itemId = Model.Id })");
}
$(function(){
setInterval(ReloadComments, 10000);
ReloadComments();
});
</script>
您的操作方法和局部视图无需编辑。
我们在项目中做了类似的事情。 首先,我们有两种操作方法,一种是获取数据(不包含任何与视图相关的东西),然后将其传递给其他具有视图的方法,它什么也不做,只能直接获取输入并渲染视图。
上下文是我们有一个计时器,该计时器将在特定间隔内调用ajax请求并将数据传递给操作(具有视图),该操作将在后台更新视图。
希望我说清楚。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.