Adding images within Html.ActionLink

user3913686 picture user3913686 · Oct 6, 2014 · Viewed 66.3k times · Source

I was trying to create an option to switch between a list view and widget view in ASP.net MVC (with razor view engine).

However, I am having some trouble trying to both add an image, as well as scale it to the 'correct height' (the same height as the next next to it).

I was looking to create something like:

Desired Result:

---------------------------------------------------------------------------------

[≡­] List View | [+] Widget View

---------------------------------------------------------------------------------

where the [≡] and [+] were actually small icon images.

Attempts so far include:

The action link was something like:

@Html.ActionLink("List View", "listView",  
    new { @style = "background-image:url('~/Content/Images/listIcon.png')" },null)

which only displayed the text.

I also tried creating the actionlink like:

<img src="~/Content/Images/listIcon.png" />@Html.ActionLink("List View", "Index")

but this resolved in

a) the image wasn't part of the link; and

b) the image was almost twice the size of the text (similar to diagram below)

 _    _               _    _
|      |             |      |
| icon |             | icon |
|_    _| List View | |_    _| Widget View

I wouldn't even mind trying to create it like:

Alternative:

---------------------------------------------------------------------------------

 _    _               _    _
|      |             |      |
| icon | List View | | icon | Widget View
|_    _|             |_    _| 

if I had to.

Would anyone know/advise how to solve/create this?

Answer

Win picture Win · Oct 6, 2014

You can use Url.Action for hyperlink and Url.Content for image source.

Then you can style the appearance with CSS.

enter image description here

<ul class="links">
    <li>
       <a href="@Url.Action("ListView", "Home")" title="List View" class="links">
            <img alt="List View" src="@Url.Content("~/Images/ListView.png")"> 
            List View
       </a>
    </li>
    <li>
       <a href="@Url.Action("WidgetView", "Home")" title="Widget View" class="links">
            <img alt="Widget View" src="@Url.Content("~/Images/WidgetView.png")"> 
            Widget View
       </a>
    </li>
</ul>
<style type="text/css">
    ul.links {
        list-style-type: none;
    }    
        ul.links li {
            display: inline-block;
            border-left: 1px solid black;
            padding-left: 10px;
            margin-left: 10px;
        }    
            ul.links li:first-child {
                border-left: 0;
                padding-left: 0;
                margin-left: 0;
            }
</style>