views:

26

answers:

2

Is it possible in MVC2 to create an anchor tag that contains values from ViewData?

e.g.

<a href="mailto:<%: ViewData["Email"] %>">Send Email</a>

This code above doesn't render and just throws an exception?

+2  A: 

Yes it is.

Moreover the default template will render that field exactly as you wrote if you use the Display Html extensions and an associated ViewModel. Just decorate the field in the model with the right DataType attribute

[DataType(DataType.EmailAddress)]
public string EmailAddress { get; set; }

Please see this post series for further informations.

EDIT:

Suppose you have the following ViewModel

public class CustomerModel {
    public string CustomerName { get; set; }

    [DataType(DataType.EmailAddress)]
    public string EmailAddress { get; set; }
}

and inside your Controller the following Action

[HttpGet]
public ActionResult ViewCustomer( int id ) {
    CustomerModel cm = LoadCustomerByID( id );
    return View( cm );
}

you can have a view named Viewcustomer.aspx that is strong typed to an instance of CustomerModel and just have this code in the view

<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<MyApp.CustomerModel>" %>

<asp:Content ContentPlaceHolderID="MainContent" runat="server">
    <%= Html.DisplayForModel() %>
</asp:Content>

Please take a coffe and get time to read that article series. It's very easy and can address more than what I am trying to write in this small post. ;)

Hope it helps!

Lorenzo
Can you point me at any more information? I want to add more than just email address into the "mailto" link, but I can't get it to work!
BlueChippy
@BlueChippy: Look at my post edit
Lorenzo
+1  A: 

The answer here is not as complicated as many would think.. it's simply a Quote (") problem:

Try changing your outer quotes to single quotes.. It terminates the string when you use " quotes in your markup aswell as in the ["Email"]... :)

<a href='mailto:<%: ViewData["Email"] %>'>Send Email</a>
Yngve B. Nilsen
Thanks Yngve B. Nilsen: You actually read the question!This isn't part of a model (well, it is, but thats irrelevant) - its to create a clickable link that will pop-up an email on the user side when the server doesn't have SMTP.My mistake was that when I used single quotes ' the intellisense appeared not to work. I realise now that its coded as a link and not as code.
BlueChippy
You're welcome.. Reading the question tends to be key to answer it ;)
Yngve B. Nilsen