MVC3 and JQuery - Can JQuery ajax method display an image generated in the controller?
Is it possible to use the JQuery ajax method to pass parameters into a controller, have the action in the controller return an image and display that image back to the user?
$.ajax({
type: 'POST',
url: '/Controller/Action',
data: { 'parameter1': '\'' + parameter1Value + '\'', 'parameter2': '\'' + parameter1Value + '\'', 'parameter3': '\'' + parameter1Value },
dataType: 'image' /* Can ajax return an image? */,
success: function (imageResults) {
// Do something
},
error: function (xhr, status, error) {
// Do something else
}
}
My goal is to generate a dynamic image based on parameters in the form and display that image back t开发者_如何学编程o the user. In addtion, ad added bonus would be to fire the ajaxstart and ajaxstop handling used by other ajax calls on the page.
Don't AJAX controller actions that return images or files or something. A much easier solution is the following:
$('body').append(
$('<img/>', {
src: '@Url.Action("Action", "Controller")?parameter1=' + encodeURIComponent(parameter1Value) + '¶meter2=' + encodeURIComponent(parameter2Value),
alt: 'some image'
})
);
This simply dynamically injects the following <img>
tag to the end of the <body>
(you could of course adapt the location if you don't like the body):
<img src="/Controller/Action/?parameter1=foo¶meter2=bar" alt="some image" />
The browser will do the rest. Just ensure that the controller action returns a File
result.
Also if those images are dynamically generated each time, IE could cause certain PITAs as it might cache them. To bust the cache append a random timestamp to the url:
$('body').append(
$('<img/>', {
src: '@Url.Action("Action", "Controller")?parameter1=' + encodeURIComponent(parameter1Value) + '¶meter2=' + encodeURIComponent(parameter2Value) + '&cacheBuster=' + encodeURIComponent((new Date()).getTime()),
alt: 'some image'
})
);
精彩评论