如何使用 AJAX 和 ASP.NET MVC3 构建相册网页






4.82/5 (3投票s)
学习如何构建一个界面,允许你滚动浏览相册中的缩略图并查看每个选定的图像。
引言
查看图像集(如相册)是许多 Web 应用程序的常见功能。在本文中,我们将介绍如何在 ASP.NET MVC 3 环境中使用 Unobtrusive AJAX 快速构建此功能。 具体来说,我们希望我们的应用程序具有以下功能
- 滚动条用于查看集合或相册中的缩略图。
- 页面的主要部分,允许你查看选定的图像。
- 需要突出显示选定的缩略图。
背景
此任务的棘手之处在于,我们需要能够动态构建可点击的缩略图,这些缩略图可以进行适当的操作调用来加载所选图像。
Using the Code
要使我们的相册页面正常工作,有很多活动部件。我们需要设置模型,然后设置控制器和视图。但首先,让我们处理引用和 CSS 类。 在你的 _Layout 页面中,请确保你引用了以下 jQuery 文件
- jquery-1.5.1.min.js
- jquery.unobtrusive-ajax.min.js
在 web.config 文件中,你还必须有一个应用程序设置,允许使用 Unobtrusive AJAX
<add key="UnobtrusiveJavaScriptEnabled" value="true"/>
在你的 CSS 类中,我们需要一个样式来突出显示点击的图像。
img.highlighted {
border: 2px solid blue;
}
模型
我们需要添加到模型文件夹的第一个类是用于操作链接的 HTML 辅助方法。 此代码稍后将用于为缩略图创建 HTML img 标签。
public static class ImageActionLinkHelper
{
public static IHtmlString ImageActionLink(this AjaxHelper helper, string imageUrl, string altText, string titleText, string actionName, object routeValues, AjaxOptions ajaxOptions)
{
var builder = new TagBuilder("img");
builder.MergeAttribute("src", imageUrl);
builder.MergeAttribute("alt", altText);
builder.MergeAttribute("title", titleText);
var link = helper.ActionLink("[replaceme]", actionName, routeValues, ajaxOptions);
return MvcHtmlString.Create(link.ToString().Replace("[replaceme]", builder.ToString(TagRenderMode.SelfClosing)));
}
}
接下来是我们的 Image 模型,它将包含图像对象本身以及图像的名称。你可以随意添加你认为应该与图像一起出现的任何其他字段。这里最重要的方法是检索图像。在演示示例中,我从本地硬盘驱动器检索文件,但你可以轻松地修改此代码以从数据库检索。另一个重要的函数返回缩略图,从而最大限度地减少服务器和客户端之间的网络流量,从而提高性能。
public class YourImage
{
public string ImageID { get; set; }
public byte[] ImageBytes { get; set; }
public static byte[] GetImage(YourImage yourImage, bool isThumbnail)
{
byte[] image = yourImage.ImageBytes;
// convert to thumbnail if necessary
if (isThumbnail)
{
MemoryStream ms = new MemoryStream(image);
Image returnImage = Image.FromStream(ms);
// convert to thumbnail to improve loading time and reduce memory usage
returnImage = returnImage.GetThumbnailImage(100, 100, ThumbnailCallback, IntPtr.Zero);
MemoryStream output = new MemoryStream();
returnImage.Save(output, ImageFormat.Jpeg);
return output.ToArray();
}
return image;
}
public static List<YourImage> GetImageList(string folder)
{
List<YourImage> imList = new List<YourImage>();
string[] fileEntries = Directory.GetFiles(folder);
foreach (string picturePath in fileEntries)
{
YourImage urImage = new YourImage();
string pictureName = picturePath.Substring(picturePath.LastIndexOf("\\") + 1, (picturePath.Length - picturePath.LastIndexOf("\\") - 1));
urImage.ImageID = pictureName;
Image currImage = Image.FromFile(picturePath);
MemoryStream output = new MemoryStream();
currImage.Save(output, ImageFormat.Jpeg);
urImage.ImageBytes = output.ToArray();
imList.Add(urImage);
}
return imList;
}
// Other code ommited for brevity
}
控制器 (Controller)
接下来是控制器的代码,该代码相当小,以便可以提取缩略图列表以及选定的图像。
public class ImageController : Controller
{
//
// GET: /Image/
public ActionResult Index()
{
string folder = ConfigurationManager.AppSettings["ImagesFolder"];
List<YourImage> imageList = YourImage.GetImageList(folder);
Session["ImageList"] = imageList;
YourImage currImage = imageList.FirstOrDefault();
TempData["CurrentImage"] = currImage;
return View(imageList);
}
public ActionResult GetYourImage(string imageName, bool isThumbnail)
{
// retrieve the object
List<YourImage> shlist = (List<YourImage>)Session["ImageList"];
YourImage shi = YourImage.GetYourImageFromList(imageName, shlist);
byte[] image = YourImage.GetImage(shi, isThumbnail);
if (image == null)
return null;
else
return File(image, "image/jpg", imageName);
}
public ActionResult ImageDetails(string imageName)
{
List<YourImage> shlist = (List<YourImage>)Session["ImageList"];
YourImage shi = YourImage.GetYourImageFromList(imageName, shlist);
return PartialView(shi);
}
}
视图
首先是 Index 视图,其中包含大部分内容,缩略图列表以及选定的图像部分。 首先,我们需要放置一些 jQuery 以在选定的缩略图之间切换。 你可以将其添加到 Index 视图的顶部。
$(function () {
$('#select-form img').click(
function () {
// Set the form value
$('#image-value').val($(this).attr('data-value'));
// Unhighlight all the images
$('#select-form img').removeClass('highlighted');
// Highlight the newly selected image
$(this).addClass('highlighted');
});
});
最关键的部分是将在 for 循环内生成的缩略图链接,因为你在每个缩略图上进行迭代。 在这里,操作链接是嵌套的,因为我们需要为图像生成源 URL,以及调用操作以更新所选图像的超链接。 AjaxOptions
指示操作结果将在何处呈现,从而替换 currentFullImage <div>
中的 html 这是我们的自定义 HTML 扩展发挥作用的部分。 确保 div 的名称与 UpdateTargetId
参数匹配。
@Ajax.ImageActionLink(@Url.Action("GetYourImage", "Image", new { imageName = item.ImageID, isThumbnail = true }),
"no image",
"NoImageTitle",
"ImageDetails",
new { imageName = item.ImageID },
new AjaxOptions { UpdateTargetId = "currentFullImage", InsertionMode = InsertionMode.Replace })
下一个视图是 ImageDetails 视图,其中显示了选定的图像。
@model ImageAlbumDemo.Models.YourImage
<br/>
<div id="currentFullImage">
<img src="@Url.Action("GetYourImage", "Image", new { imageName = Model.ImageID, isThumbnail = false })"
alt="No Image" width="100%" height="100%" id="imgMain" />
</div>
现在我们准备好了,这是最终结果!
关注点
现在应用程序正在运行,请仔细查看 ImageActionLink
函数生成的 HTML。 缩略图图像对象位于超链接元素 <a> 内。
<a data-ajax="true" data-ajax-mode="replace" data-ajax-update="#currentFullImage" href="https://codeproject.org.cn/Image/ImageDetails?imageName=clip-art-circus-465619.jpg">
<img alt="no image" src="https://codeproject.org.cn/Image/GetYourImage?imageName=clip-art-circus-465619.jpg&isThumbnail=True" title="NoImageTitle" />
</a>
历史
目前尚无更新。