Search code examples
htmlhref

How do you make the href of an anchor tag dependent on a class property?


I've created a page for a table of customers in ASP.NET CORE Razor WebApp, and I'm trying to implement download links for images and files from a database. The customer class has the string property "Picture" that holds the image URL. Since the database is ever growing, I can't hardcode a URL into an anchor tag, but I'm having trouble setting the href to a customer's Picture property. Here's a snippet of one of the ways I tried:

@foreach (var item in Model.Customer)
{
    <tr>
        <td>
            <a id="downloadPictureLnk" download="Customer_Picture.png" href=item.Picture>Download Picture</a>
        <td>
    <tr>
}

However, href is just appending item.Picture to the existing URL to generate a link. The browser downloads something, but says it's an empty file. I've also tried this:

  @foreach (var item in Model.Customer)
{
    <tr>
        <td>
            <a id="downloadPictureLnk" href="" onclick=Download()>Download Picture</a>
        <td>
    <tr>
}
<script>
    function Download() {
        downloadPictureLink = document.getElementById('downloadPictureLnk');
        downloadPictureLink.href = item.Picture;
        downloadPictureLink.download = String.Format("{0}_Picture", item.Name);
    }
</script>

This doesn't even generate a link.
Where am I going wrong/is there another way to go about this? I've been reading through the similar questions other users have asked, but everyone seems to have a static URL they can put directly in the anchor tag. I'm new at this, so any help is much appreciated!

Update
href=@item.Picture
This is what I was missing, thanks for the help


Solution

  • Im not sure, havent used razor in a while, but I think its something like <a href="@item.Picture">