gpt4 book ai didi

jquery - MVC,使用AJAX/JQUERY异步显示图像列表

转载 作者:行者123 更新时间:2023-12-03 22:59:58 25 4
gpt4 key购买 nike

我有一个网站,我从数据库加载图像(缩略图)列表。问题是图像显示速度相当慢,因为使用 Url.Action 获取每个缩略图相当耗时(当遍历整个 MVC 管道时)。

因此,我想使用 Ajax 和 JQUERY 异步加载图像,同时显示每个图像的标准加载图像 (ajaxloag.info),直到图像加载完毕。提出了类似的问题here ,但我需要一个更完整的示例,因为我对 MVC 和 JQUERY 非常陌生。

提前致谢,

查看(partialView)

// Foreach product, display the corresponding thumbnail
<% foreach (var p in Model)
{ %>
.
.

<img width="100" src="<%= Url.Action( "Thumbnail", "Products", new { productId = p.ID } ) %>" alt="" />

Controller

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;
}
}

更新 - 包含 Javascript 的父 View

<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>

最佳答案

您可以使用 HTML5 data-* 属性:

<img width="100" 
src="ajax-loader.gif"
class="async"
data-img-url="<%= Url.Action("Thumbnail", "Products", new { productId = p.ID }) %>"
/>

然后在一个单独的js文件中:

$(function() {
$('.async').load(function() {
$(this).unbind('load');
this.src = $(this).attr('data-img-url');
});
});

此外,我会使用编辑器/显示模板,而不是在 View 中编写 foreach 循环:

<%= Html.DisplayForModel() %>

并在相应的显示模板中放置图像:

<%@ Control 
Language="C#"
Inherits="System.Web.Mvc.ViewUserControl<AppName.Models.Product>"
%>
<img width="100"
src="ajax-loader.gif"
class="async"
data-img-url="<%= Url.Action("Thumbnail", "Products", new { productId = Model.ID }) %>"
/>

关于jquery - MVC,使用AJAX/JQUERY异步显示图像列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5096575/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com