我正在尝试显示数据库中的图像,但是该图像不会填充img html属性的src。

时间:2019-05-27 16:57:18

标签: javascript c# html asp.net-mvc razor

我通过将字节数组转换为字符串将图像保存到数据库,然后尝试在视图上重新制作图像。但我想这样做是因为如果图像为空(没有图像上传),他们将获得默认的“无图像”图像。但是似乎当我尝试用剃刀在自己的视野内做出if陈述时。 img src无法在if语句中找到var。我需要它在if语句之外填充img上的src的原因是,当我提交表单时,我需要它将img数据发送回控制器中的操作,以重新转换它并将其保存在数据库中。 / p>

我尝试以不同的方式修复视图,最好的方法是在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。

2 个答案:

答案 0 :(得分:0)

您有:

<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");时,它将无法找到该元素,因为它尚未加载。

答案 1 :(得分:0)

我发现我在模型中创建了一个新变量,并在我的操作中将字符串添加到了该变量中,以加载页面,然后将其设置为img src。谢谢您的帮助!