I am at beginner level for using Jquery.
Problem : so the problem is that, I have to add “choose file” for each of the element’s inside a tag. And display the image after selecting it inside the tag. But Has this is this list of elements using for each loop, it cannot different between the id property.
please see the images and code for reference and help me out,
Thank You !!!
[.cshtml]
@if (Model.DailyMenuProducts != null && Model.DailyMenuProducts.Count > 0)
{
@for (int i = 0; i < Model.DailyMenuProducts.Count; i++)
{
<li class="list-group-item">
<input asp-for="@Model.DailyMenuProducts[i].IsChecked" type="checkbox" />
<label asp-for="@Model.DailyMenuProducts[i].ProductId"> @Model.DailyMenuProducts[i].ProductName</label>
<input type="hidden" asp-for="@Model.DailyMenuProducts[i].ProductId"/>
<input type="hidden" asp-for="@Model.DailyMenuProducts[i].ProductName" asp-route-productId/>
<div class="uploadFile float-end">
<label for="productImage">
<img id="imageViewer" width="50" height="50" style="border: 1px solid #000000; cursor:pointer;" />
</label>
<input asp-for="@Model.DailyMenuProducts[i].ProductImage" asp-for-ProductId="@Model.DailyMenuProducts[i].ProductId" type="file" id="productImage" style="display:none; visibility:none" onchange="getImage(this.value);"/>
</div>
</li>
}
[.js]
$(".uploadFile").on('change', function () {
console.log('new file uploaded')
//var array = $("#productImage").getIdArray();
var file_data = $("#productImage").prop("files")[0];
var files = event.target.files
$("#imageViewer").attr("src", window.URL.createObjectURL(files[0]));
var form_data = new FormData();
var product_Id = (this.ProductId) ;
var viewModel = { ProductId: product_Id, ProductImage: file_data};
form_data.append("file", file_data);
$.ajax({
url: "/DailyMenuPlanner/AddPhoto",
cache: false,
contentType: false,
processData: false,
data: viewModel,
type: 'post',
success: function (result) {
if (result.success == true) { alert("success!"); }
else { alert("fail!"); }
}
});
});