使用Ajax/MVC在表行中显示图像
本文关键字:显示 显示图 图像 Ajax MVC 使用 | 更新日期: 2023-09-27 18:01:24
开门见山,在我的控制器中有这样的内容:
return base.File(getSomeImageBitmap, "image/jpeg");
在使用@Html.ActionLink
的新窗口中显示图像。但是,我想在单击链接时将图像直接填充到表中。所以,我尝试了这个方法:
@Ajax.ActionLink("View", "Image", "Controller", new { id = t.id, id2 = t.id2},
new AjaxOptions { UpdateTargetId = "myImage", HttpMethod = "GET" }
<div id="myImage"></div>
给定t
是模型数组中的对象,这种方法有两个缺点。首先,它将未编码的位图显示为文本,而不是图像。其次,它每次都将数据填充到表中的第一个div中。
我的下一个策略是创建一个PartialView并生成唯一的DIV id,以便它们可以使用@Ajax.ActionLink
插入,但我不知道是否可以使其像那样工作。
最后,我试了:
<img src="@Url.Action("Image", "Controller", new { id = t.id, id2 = t.id2 })" alt="Some Image" />
这工作完美,减去事实,它查询我的webservice多达500图像一次。我不能让这种情况发生,我只想在点击任意链接时检索图像。这可能吗?Jquery和Ajax都是公平的竞争。
编辑:使用以下解决方案,它也支持隐藏图像。它只缺少加载文本:
<img hidden src="" alt="No Image" class="imagePreview" />
<script type="text/javascript">
// Handle clicking the View image link
$(".linkView").click(function (e) {
e.preventDefault();
// The link being clicked
var _this = $(this);
// Find the closest imagePreview to the link
var image = _this.closest("tr").find("img.imagePreview");
if (image.is(':visible')) {
// If the image is visible, hide it
_this.text("View");
image.hide();
} else {
// If image is not visible, show it
_this.text("Hide");
image.show();
// If the image src has not been set, set it to the link href
// By not clearing the src attribute, we can show/hide without loading the image again
if (image.attr("src") == "") {
image.attr("src", _this.attr("href"));
}
}
});
</script>
问题是,您的代码将生成多个id为"myImage"的div。这不是有效的HTML。Id值必须是唯一的
我建议你使用一个正常的链接,并编写一个jQuery代码来处理当链接被点击时图像的加载。
@Html.ActionLink("View", "Image", "Home", new { id = t.id, id2 = t.id2},
new {@class="linkView"})
<img class="imagePreview"/>
这将呈现一个css类为linkView
的普通链接和一个css类为imagePreview
的图像标签。
现在听这些链接上的click
事件,防止默认的点击行为(导航到href值),更新图像src属性。
您可以使用closest()
方法来获取对当前表行(链接所属的位置)的引用,并使用find()
方法来获取对我们的图像的引用。
$(function(){
$(".linkView").click(function(e){
e.preventDefault();
var _this=$(this);
_this.closest("tr").find("img.imagePreview").attr("src",_this.attr("href"));
});
});