1

I was wondering if I have a model class like this:

public class Contact
{
    public string Name { get; set; }
    public string[] Emails { get; set; }
}

In my View I use DisplayFor, so it does show all emails, but just as one string.

@Html.DisplayFor(modelItem => item.Emails)

[email protected]@[email protected]

Is there some kind of DisplayFormat attribute that I can apply to Emails property, so that it would display all emails for a single contact, separated by a comma, like this:

[email protected], [email protected], [email protected]

Dont really want to use foreach(var email in Model.Email) in my view for this simple operation.

Thanks.

3
  • try adding the appropriate programming language tag. In PHP i would use something like implode(Emails, ', '), i gues this language has a similar feature Commented Aug 3, 2012 at 18:41
  • You could create an editor template. Check this out: coding-in.net/asp-net-mvc-3-how-to-use-editortemplates Commented Aug 3, 2012 at 18:48
  • Thanks Andre, I would nee the editor too :) Commented Aug 3, 2012 at 23:49

2 Answers 2

3

How about adding another string property to the ViewModel to represent a comma seperated version of the string array and use that in the view

public class Contact
{
    public string Name { get; set; }
    public string[] Emails { get; set; }
    public string EmailsCommaSeperated 
    { 
      get
      {
        return String.Join(",",Emails);
      }
    }
}

and use it as

@Html.DisplayFor(modelItem => item.EmailsCommaSeperated)
Sign up to request clarification or add additional context in comments.

4 Comments

Wouldn't @Html.DisplayFor(modelItem => String.Join(", ", item.Emails)) work as well?
@AndreCalil: It is same thing. I want to keep it to the POCO(ViewModel) so that the View looks clean and readable without so many function calls.
I see. As this class is a model, and not a simple view model, I'd prefer not to add view logic to it. However, it's a minor decision. +1 for the straightforward suggestion
@AndreCalil: I edited the answer to include the ViewModel word.
0

You will need to create a custom helper.

This video tutorial will help you: http://pluralsight.com/training/players/PSODPlayer?author=scott-allen&name=mvc3-building-views&mode=live&clip=6&course=aspdotnet-mvc3-intro

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.