I cannot use the parameter passed to my javascript method in lambda expression by trying several ways as shown below. How can I use id parameter in the expression below? Thanks in advance.
There is a hyperlink in the FileName and I pass the ID parameter to the Javascript method successfully:
<a onclick="downloadFile(@p.ID);">@p.FileName</a>
function downloadFile(id) {
$.fancybox({
//This works: (p.ID == 82)
content: '<img src="data:image/png;base64,@System.Convert.ToBase64String(Model.FileAttachments.FirstOrDefault(p => p.ID == 82 ).FileData)" alt=""/>',
//They are not works: (p.ID == id / p.ID == @id / p.ID == this.id)
content: '<img src="data:image/png;base64,@System.Convert.ToBase64String(Model.FileAttachments.FirstOrDefault(p => p.ID == id ).FileData)" alt=""/>',
content: '<img src="data:image/png;base64,@System.Convert.ToBase64String(Model.FileAttachments.FirstOrDefault(p => p.ID == @id ).FileData)" alt=""/>',
content: '<img src="data:image/png;base64,@System.Convert.ToBase64String(Model.FileAttachments.FirstOrDefault(p => p.ID == this.id ).FileData)" alt=""/>',
type: "html"
});
}
Update: Here is the Ajax method that I used before
function downloadFile(id) {
$.ajax({
url: "/Issue/RenderImage",
type: "POST",
data: JSON.stringify({ 'id': id }),
dataType: "json",
traditional: true,
contentType: "application/json; charset=utf-8",
success: function (response) {
$.fancybox({
content: '<img height="200" width="250" src="data:image/png;base64,' + response.Image + '" />',
type: "html"
//});
},
error: function () {
alert("an error has occured!!!");
}
});
}
If somebody told you there is no need ajax, it seems the image data can be post to page,just like dictionary,you can change your code ,and put your
Model.FileAttachments
to be part of js,just likeAnd you said you want to download other file types (pdf, etc),it can not be like image,you can use code like these if there is no limited to download the file
I posted the final working status of the code by modifying the @Sky Fang's answer so that someone need to use it. I also pass the title parameter to the javascript method.
View: