weixin_33724046 2015-07-10 23:06 采纳率: 0%
浏览 69

带有Ajax的jQuery FancyBox

I have look at many web sites and many pages on Stackoverflow, but none of them has solved my problem yet. Simply, I have a hyperlink and I want to retrieve an image from database via Ajax call and then display it on FancyBox popup. I also tried many different combinations of Javascript and Controller action methods, but have not managed so display the downloaded file properly. Could you please have a look at my code and give a working example containing all the necessary methods in View and in Controller? On the other hand, it would be better to open a dialog for the other file types (i.e. excel, pdf) while opening FancyBox for image files.

View:

<a onclick="downloadFile(@Model.ID);">@Model.FileName</a>


function downloadFile(id) {     
    $.ajax({
        url: "/Issue/RenderImage?ID=" + id,
        async: true,
        type: "POST",
        dataType: "json",
        contentType: "application/json; charset=utf-8",
        success: function (response) {
            $('#fancybox-inner').html('<img height="200" width="250" src="data:image/png;base64,' + response + '" />');
        }       
    });
}


Controller: There is no problem regarding to the method in the Controller and it returns the image properly.

[HttpPost]
public virtual JsonResult RenderImage(int id)
{
    string str = System.Convert.ToBase64String(repository.FileAttachments.FirstOrDefault(p => p.ID == id).FileData, 0, repository.FileAttachments.FirstOrDefault(p => p.ID == id).FileData.Length);
    return Json(new { Image = str, JsonRequestBehavior.AllowGet });
}
  • 写回答

2条回答 默认 最新

  • weixin_33739541 2015-07-11 00:59
    关注

    This should work. Looks like image is stored as JSON. If so, I think you should convert it back to Base64 before sending it to the browser. See http://mobile.cs.fsu.edu/converting-images-to-json-objects/

    function downloadFile(id) {
        $('#fancybox-inner').html('<img height="200" width="250" src="/Issue/RenderImage?ID='+id+'" />');
    }
    
    评论

报告相同问题?