I found an answer here, but it uses a JavaScript. I am trying to apply this script but in razor codes but I don't know how to do it, I searched/googled with different keyword but all answers don't use a razor code. Can anyone help me ?
Here is a part of the cshtml page.
<tr>
<td><label>Image</label></td>
<td>
<script>
function ImgPre(input) {
if (input.files[0]) {
var uploadImg = new FileReader();
uploadImg.onload = function (displayImg) {
$("#imagePreviewer").attr('src', displayImg.target.result);
}
uploadImg.readAsDataURL(input.files[0]);
}
}
</script>
<input type="file" accept="image/*" asp-for="Image" onchange="ImgPre(this)" />
@{
string base64 = "";
if (Model.Image != null)
{
base64 = Convert.ToBase64String(Model.Image);
}
var imgSrc = String.Format("data:image/jpeg;base64,{0}", base64);
}
<img id="imagePreviewer" src="@imgSrc" width="150" />
</td>
</tr>
how can I write the code in the <script></script> tag to be similar to the one with @{ }
I have been struggling to find a solution but I can't find any. Can someone help me, please ?
You can write javascript in your cshtml file by surrounding the with @section Scripts{}.
It should looks like
<input type="file" id=" ImgUpload" onchange="ImgPre(this)" />
<button id="butImg">Upload</button>
<p>
<img id="ImgPreview" />
</p>
@section Scripts{
<script>
function ImgPre(input) {
if (input.files[0]) {
var uploadimg = new FileReader();
uploadimg.onload = function(displayimg) {
$("#ImgPreview").attr('src', displayimg.target.result);
}
uploadimg.readAsDataURL(input.files[0]);
}
}
</script>
}