简体   繁体   中英

I'm trying to display an image from my database, but the image wont populate the src of the img html attribute

I have an image saved to a database by converting to a byte array to a string then i am trying to remake the image on the view. But I wanted to make it for if the image was null(no image upload) that they will get a default "no image" image. But it seems when i try to make an if statement within my view with razor. The img src is not able to find the var in the if statement. The reason i need it to fill the src on the img outside of the if statement is because when i submit the form i need it to send the img data back to the action in the controller to reconvert it and save it on the database.

I trying a view different ways to fix it, the best i can do it make scripts inside my if statement. but it still will not connect to my 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=""/>

when i inspect the page the script has the image converted back into the right format it just wont send it to the img src.

You have:

<script>
    var img = getElementById("ImagePath").src;
    img.src = "@imgSrc";
</script>

That looks like it is setting img.src.src, which doesn't make sense. That should probably be this, correct? :

<script>
    var img = getElementById("ImagePath");
    img.src = "@imgSrc";
</script>

And you could also make sure to remove all line breaks:

<script>
    var img = getElementById("ImagePath");
    var imgSrc = "@imgSrc";
    img.src = imgSrc.replace(/[\r|\n]/gm,'');
</script>

Also, as noted by Divya, your image element should come before your script tags, otherwise when you have getElementById("ImagePath"); , it won't be able to find that element, since it has not loaded yet.

I figured it out i made a new vareriable in my model and added the string to it in my action that loads the page then just set that as the img src. Thank you for the help tho!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM