【发布时间】:2011-02-24 06:17:06
【问题描述】:
我有一个站点,我在其中从数据库加载图像列表(缩略图)。问题是图像的显示速度很慢,因为使用 Url.Action 获取每个缩略图相当耗时(在遍历整个 MVC 管道时)。
因此,我想使用 Ajax 和 JQUERY 异步加载图像,同时显示每个图像的标准加载图像 (ajaxloag.info),直到图像被加载。 here 提出了一个类似的问题,但我需要一个更完整的示例,因为我对 MVC 和 JQUERY 非常陌生。
提前致谢,
视图(部分视图)
// Foreach product, display the corresponding thumbnail
<% foreach (var p in Model)
{ %>
.
.
<img width="100" src="<%= Url.Action( "Thumbnail", "Products", new { productId = p.ID } ) %>" alt="" />
控制器
public ActionResult Thumbnail(string productId)
{
try
{
Guid pid = new Guid(productId);
byte[] thumbnailData = _productsRepository.GetProductThumbnail(pid);
if (thumbnailData != null)
{
return File(thumbnailData, "image/jpg");
}
else
{
return File(@"../Content/missingproduct.png", "image/jpg");
}
}
catch (Exception e)
{
throw e;
}
}
UPDATE - 包含 Javascript 的父视图
<script type="text/javascript">
$(document).ready(function()
{
getContentTab (1);
});
function getContentTab(index)
{
var criteria = {
categoryId : "<%: ViewBag.Header %>",
tabIndex: index,
searchString : "<%: ViewBag.SearchString %>"
};
var url='<%= Url.Content("~/Products/GetAjaxTab") %>'
var targetDiv = "#listContent";
var ajaxLoadUrl = '<%: Url.Content("/Content") %>/ajax-loader.gif';
var ajaxLoading = "<img id='ajax-loader' src='" + ajaxLoadUrl + "' align='left' height='28' width='28' />";
$(targetDiv).html("<div>" + ajaxLoading + " Loading...</div>");
tag in respect to the callback.
$.get(url, criteria, function(result)
{
$(targetDiv).html(result);
});
}
function AjaxStart()
{
$('#listContent').mask('Opdaterer');
}
function AjaxEnd()
{
$('#listContent').unmask();
}
$(function () {
$('.async').load(function () {
$(this).unbind('load');
this.src = $(this).attr('data-img-url');
alert('2');
});
});
//]]>
</script>
【问题讨论】:
标签: jquery asp.net-mvc ajax