Simon Martin
Simon Martin

Reputation: 4231

MVC3 razor helper method to display email address with mailto passing variables

I'm trying to get a mailto link to display with the persons name rather than the actual email address.

In my details.cshtml file I have the page strongly typed to my Supplier

@model TheWorkshop.Web.Models.Supplier

but although I can use

@Html.DisplayFor(model => model.Email)

to display a mailto link with the text value the same as the mailto e.g.

< a href="mailto: [email protected]">[email protected]< /a>

What I want is to display the name of the person instead. So after hunting about I decided to try to make a Helper method

public static MvcHtmlString PrettyEmailAddress(this HtmlHelper htmlHelper, 
                                               string email, string name)
{
    var mailToLink = new TagBuilder("a");
    mailToLink.Attributes.Add("mailto", email);
    mailToLink.SetInnerText(name);

    return MvcHtmlString.Create(mailToLink.ToString());
}

but the trouble is that when I try to call it in the binding like this:

 @Html.PrettyEmailAddress(@model.Email, @model.Name))

I get a compilation error

CS0103: The name 'model' does not exist in the current context

If I pass strings instead of the @model.Email and '@model.Name` then the helper works fine, but how do I pass variables into the helper?

Upvotes: 0

Views: 2272

Answers (2)

Roath So
Roath So

Reputation: 141

Try this:

<a href="mailto:@Model.Email">@Html.ValueFor(model=>model.Email)</a>

Upvotes: 0

Darin Dimitrov
Darin Dimitrov

Reputation: 1039120

Try calling your helper like this:

@Html.PrettyEmailAddress(Model.Email, Model.Name)

Things to notice:

  • Capital M
  • No need to use @ because you are already on the server

Also you probably wanna replace:

mailToLink.Attributes.Add("mailto", email);

with:

mailToLink.Attributes.Add("href", string.Format("mailto: {0}", email));

in order to achieve the desired result.

Upvotes: 1

Related Questions