[英]I'm trying to display an image from my database, but the image wont populate the src of the img html attribute
通過將字節數組轉換為字符串,我將圖像保存到數據庫然后我嘗試在視圖上重新制作圖像。 但我想讓它成為如果圖像為空(沒有圖像上傳),他們將獲得默認的“無圖像”圖像。 但是當我嘗試用剃須刀在我的視野中制作一個if語句時。 img src無法在if語句中找到var。 我需要它來填充if語句之外的img上的src的原因是因為當我提交表單時我需要它將img數據發送回控制器中的操作以重新轉換它並將其保存在數據庫中。
我嘗試了一種不同的方法來修復它,我可以做的最好的方法是在我的if語句中創建腳本。 但它仍然無法連接到我的img src。
<!--Remaking the image from a stromg to a char
array to a byte array to a imagefrom the
database to the original image-->
@if (Model.ImagePath != null)
{
char[] imageChars = Model.ImagePath.ToCharArray();
byte[] imageBytes = imageChars.Select(b => (byte)b).ToArray();
var base64 = Convert.ToBase64String(imageBytes);
var imgSrc = String.Format("data:image/gif;base64,{0}", base64);
<script>
var img = getElementById("ImagePath").src;
img.src = "@imgSrc";
</script>
}
else
{
<script>
var img = getElementById("ImagePath");
img.src = "~/Content/no-image-icon.jpg";
getElementById("ImagePath").width = "100";
getElementById("ImagePath").height = "100";
</script>
}
<img id="ImagePath" alt=""/>
當我檢查頁面時,腳本將圖像轉換回正確的格式,它只是不會將它發送到img src。
你有:
<script>
var img = getElementById("ImagePath").src;
img.src = "@imgSrc";
</script>
看起來它正在設置img.src.src,這沒有意義。 這應該是這個,對嗎? :
<script>
var img = getElementById("ImagePath");
img.src = "@imgSrc";
</script>
您還可以確保刪除所有換行符:
<script>
var img = getElementById("ImagePath");
var imgSrc = "@imgSrc";
img.src = imgSrc.replace(/[\r|\n]/gm,'');
</script>
此外,正如Divya所述,您的圖像元素應該在腳本標記之前,否則當您有getElementById("ImagePath");
,它將無法找到該元素,因為它尚未加載。
我想通了我在我的模型中做了一個新的vareriable並在我的動作中添加了字符串,加載頁面然后將其設置為img src。 謝謝你的幫助!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.