Can't load image in modal using Partial View by transporting data by Model

Viewed 77

I want to use Partial View to load modal with image from wwwroot folder. It works with explicitly setting imgage source to directory of image. It doesn't work with using a model with property that holds path to image.

I checked string that is created and save to model. To me it looks good.

Model that is send to Partial View:

public class ImagePath
    {
        public string Path { get; set; }
    }

Partial View:

//that image is displayed
<img class="img-fluid" src="~/images/Equipment/8711-rys.jpg" alt="Alternate Text" />

//that image isn't displayed
<img class="img-fluid" src="@Model.Path" alt="Alternate Text" />

Get function that calls and returns Partial View:

public PartialViewResult OnGetModalImage(string path)
        {
            var pathToImage = "~/images/Equipment" + path;
            ImagePath = new ImagePath
            {
                Path = pathToImage
            };
            return Partial("_ModalImage", ImagePath);
        }

View code:

<script type="text/javascript">
$(function () {
            $('#myInput').on('click', function () {
                $('.modal-body').load(`/treeview/modalimage?path=${'/8711-rys.jpg'}`);
            });
        })
</script>

<div id="imgModal" class="modal fade" tabindex="-1" role="dialog" aria-hidden="true">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Nazwa narzedzia</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
            </div>
        </div>
    </div>
</div>
1 Answers

It doesn't work with using a model with property that holds path to image.

If you checked the rendered html source of <img> tag(s) in browser side, you would find it look like below.

enter image description here

To make the second <img> tag render well, you can use @Url.Content(Model.Path) to convert a virtual (relative, starting with ~/) path to an application absolute path.

<img class="img-fluid" src="@Url.Content(Model.Path)" alt="Alternate Text" />

Another approach is setting pathToImage to "/images/Equipment" + path, like below.

var pathToImage = "/images/Equipment" + path;
ImagePath = new ImagePath
{
    Path = pathToImage
};
Related