我有一个网站,我从数据库中加载图像列表(缩略图).问题是图像显示得相当慢,因为使用Url.Action获取每个缩略图相当耗时(当通过整个MVC管道时).
因此,我想用Ajax& amp;异步加载图像. 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="" />
调节器
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>
解决方法
您可以使用HTML5 data- *属性:
<img width="100" src="ajax-loader.gif" class="async" data-img-url="<%= Url.Action("Thumbnail",new { productId = p.ID }) %>" />
$(function() { $('.async').load(function() { $(this).unbind('load'); this.src = $(this).attr('data-img-url'); }); });
另外我会使用编辑器/显示模板而不是在视图中编写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",new { productId = Model.ID }) %>" />
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。