Reputation: 173
I am working with ASP.net MVC for a website page in cshtml. I'm new to this & I'm having a hard time doing a simple task as I would in C#. I'm trying to load images onto my site by a field in my "categories" class. There is a field in this class called ImageFileName.
I'm able to load an image normally hardcoding like:
<img src="~/Content/Images/Dining/Dining.jpg"
[email protected]
style="width:64px;height:48px;" />
However, I want to do the same without hardcoding the file name:
<img src="~/Content/Images/" + @c.ImageFileName
[email protected]
style="width:64px;height:48px;" />
However this does not append the path string and the files do not load. I have tried putting the images in the general images folder as well, I just feel I have the wrong syntax.
Upvotes: 1
Views: 623
Reputation: 503
You're syntax is incorrect. Remember, you're rendering HTML and writing in Razor, not C#.
This:
<img src="~/Content/Images/" + @c.ImageFileName
[email protected]
style="width:64px;height:48px;" />
Should be this:
<img src="~/Content/Images/@c.ImageFileName"
alt="@c.CatName"
style="width:64px;height:48px;" />
However, as others have suggested, you might consider storing the whole path of the image in that ImageFileName
property. Your code would then be:
<img src="@c.ImageFileName"
alt="@c.CatName"
style="width:64px;height:48px;" />
Just some food for thought
Upvotes: 2
Reputation: 629
Try this (using Html.Raw helper):
<img src="@Html.Raw("~/Content/Images/" + c.ImageFileName)"
alt="@Html.Raw(c.CatName)" style="width:64px;height:48px;" />
Upvotes: 1