Reputation: 189
On a button click, I want to call a Controller method in which I create a PNG image dynamically. I want to then send that image to the view and display it for the user to see. I can't quite figure out how to properly do this, or what I'm exactly doing wrong. My code is as follows:
View
<div style="height:350px; margin:10px;">
<img id="rsDiagram" src="" alt="RS Diagram" class="partDiagram">
</div>
Controller
public ActionResult RSView(string orderNumber)
{
// I create the png and save it to wwwroot/images/
string outfile = Path.GetFullPath(Path.Combine(_hostingEnvironment.WebRootPath, "images", "RSView.png"));
string fileToSend = Convert.ToBase64String(System.IO.File.ReadAllBytes(outfile));
return Json(fileToSend);
}
Javascript
//This is called on a button click
$.ajax({
type: "GET",
url: "/Home/RSView",
data: { "orderNumber": $("#shopOrderNumber").val() },
success: function (response) {
rs.style.display = "block";
$("rsDiagram").attr("src", "data:image/png;base64," + response + '"');
},
error: function (response) {
alert(response.responseText);
}
});
Upvotes: 0
Views: 1978
Reputation: 22429
Seems your code is almost alright only little problem founded how you are binding the response on your image tag. Just replace the below line with your older one.
$("#rsDiagram").attr('src', 'data:image/png;base64,' + response);
Note: I have tried to keep all of your existing code.
So the full solution would be looks like
Controller: Same as yours
public ActionResult RSView()
{
// I create the png and save it to wwwroot/images/
string outfile = Path.GetFullPath(Path.Combine(_hostEnvironment.WebRootPath, "images", "RSView.png"));
string fileToSend = Convert.ToBase64String(System.IO.File.ReadAllBytes(outfile));
return Json(fileToSend);
}
View:
Also same, I just added a button so that anyone can test with this solution
<div style="height:350px; margin:10px;">
<img id="rsDiagram" src="" class="partDiagram">
</div>
<!-- Button for calling ajax request -->
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal">
Load Images
</button>
Javascript:
@section scripts {
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.2.1.min.js"></script>
<script>
$(document).ready(function () {
$("button").click(function (e) {
$.ajax({
type: "GET",
url: "/Home/RSView",
//data: { "orderNumber": $("#shopOrderNumber").val() },
success: function (response) {
console.log(response);
$("#rsDiagram").attr('src', 'data:image/png;base64,' + response);
},
error: function (response) {
alert(response.responseText);
}
});
});
});
</script>
}
Note: Here in
ajax
request I have commented your parameter{ "orderNumber": $("#shopOrderNumber").val()
as I am calling thecontroller
for the predefined image so that I didn't sent any parameter. Hope you get me here.
Hope it would resolve your problem.
Upvotes: 1