I want to load an image from the database when on page load and when clicking a button.
when form is loading it is working fine, but when i click the button, i need to pass the value from the dropdown and call the controller on javascript using Url.Action.
when i click the button, getting Failed to load resource: the server responded with a status of 500 ()
controller method:
public FileContentResult MyAction(int compId)
{
byte[] img = new byte[100000];
img = _unitOfWork.Company.GetAll().Where(a => a.Id == compId).
Select(a => a.PhotoAd).FirstOrDefault();
if (img == null)
{
return null;
}
return new FileContentResult(img, "img/jpg");
}
View:
<body>
<div class="col-4" >
<div class="form-group row">
<div class="col-2">
<label asp-for="forCompList.CompId">Company</label>
</div>
<div class="col-8">
@Html.DropDownListFor(m => m.forCompList.CompId, Model.CompList,
new { @class = "form-control" })
</div>
</div>
<div class="col-2 text-right">
<button class="btn btn-primary" style="background-color:forestgreen" onclick="LoadImage()">
<i class="fa fa-refresh"></i> Load Company Image</button>
</div>
<div>
<img src= '@Url.Action("MyAction", "AdImage", new{path="img/jpg", compId = ViewBag.compId})' id="AdImage"/>
</div>
</div>
</body>
@section Scripts{
<script src="~/lib/jquery/dist/jquery.min.js"></script>
<script type="text/javascript">
function LoadImage()
{
var cid = document.getElementById('forCompList_CompId').value;
window.alert(cid);
$('#AdImage').src =
'@Url.Action("MyAction", "AdImage",new{path="img/jpg"})?compId='+cid;
}
</script>
i would change ajax to this
$('#AdImage').attr('src','@Url.Action("MyAction", "AdImage")' + '?path=img/jpg&compId=' + cid);