user2619542
user2619542

Reputation: 223

How to Convert a Text to HyperLink or ActionLink in Razor View MVC C#

I am trying to display List of addresses in a table in MVC Razor view. I did that, but now i need to convert those Text to HyperLinks or Action Links where i am having a separate action controller if we click on that address.

Here is my view which displays the list of addresses in table

<table id="list" class="display"><thead>
        <tr><th>
            Available Addresses
            </th>
            <th>
                Loan Statuses
            </th>
        </tr>
        </thead>
        <tbody>

            @foreach (var im in Model.AddressAndStatus)
            {
                <tr>
                    <td>
                        @Html.DisplayFor(m => im.Address)

                    </td>
                    <td>
                        @Html.DisplayFor(m => im.Status)
                    </td>

                </tr>
            }



        </tbody>
    </table>

Instead of using the DisplayFor can we use any helper to display that as link instead of Text?

Upvotes: 2

Views: 6973

Answers (2)

hutchonoid
hutchonoid

Reputation: 33306

You would do that like this:

public static MvcHtmlString AddressLink(this HtmlHelper htmlHelper, string address)
{
    var tb = new TagBuilder("a");
    tb.Attributes.Add("href", address);
    tb.SetInnerText(address);
    return new MvcHtmlString(tb.ToString());
}

Call it from your view like this:

 @Html.AddressLink(im.Address);

ps Don't forget to use the correct namespace i.e.

 namespace System.Web.Mvc

Update:

If want a helper that has actions based on statuses you would do the following:

 public static MvcHtmlString AddressLink(this HtmlHelper htmlHelper, string address, string status)
{
    var sb = new StringBuilder();
    sb.Append(htmlHelper.ActionLink(address, status, "Controller"));
    return new MvcHtmlString(sb.ToString());
}

You would need to change the "Controller" name to yours and would call it like this:

  @Html.AddressLink(im.Address, im.Status)

Upvotes: 0

Travis J
Travis J

Reputation: 82297

Assuming that status is the link text, and address is the link target, just use plain html. There is no need to always use a helper.

<a href="@(im.Address)">@(im.Status)</a>

Upvotes: 3

Related Questions