سؤال

I would like a collection to be displayed using EditorForModel().

According to this Blog from Brad Wilson this should be a no brainer. However, it just does not work for me.

The Controller:

 public ActionResult Index() {

        var contact = new Contact() { FirstName = "Greg", LastName = "Gum", Age = 27 };
        contact.PhoneNumbers = new List<string>();
        contact.PhoneNumbers.Add("111");
        contact.PhoneNumbers.Add("222");
        return View(contact);
    }

The Class:

public class Contact
{

    public string FirstName { get; set; }
    public string LastName { get; set; }
    public int Age { get; set; }

    public List<String> PhoneNumbers { get; set; } 

}     

The View:

@model WebApplication33.Models.Contact

@Html.DisplayForModel()

This displays the other properties just fine, but not the collection. How do I get the collection to display? I have tried and tried to get this to work, as all the things I have read seem to say this should work just as the above.

هل كانت مفيدة؟

المحلول

You can create a re-usable template that will display the fields.

Create a folder called: /Views/YourController/DisplayTemplates

If the template needs to be shared across controllers: /Views/Shared/DisplayTemplates

Create a view in the DisplayTemplates folder called Contact. In that view display the four fields:

@model WebApplication33.Models.Contact
@Html.DisplayFor(m => m.FirstName);
@Html.DisplayFor(m => m.LastName);
@Html.DisplayFor(m => m.Age)
@Html.DisplayFor(m => m.PhoneNumbers)

نصائح أخرى

It seems collections are not supported out of the box as in the above example.

However, by creating a Display Template for class Contact, I can then do this:

 @model WebApplication33.Models.Contact
 @Html.DisplayFor(m => m.FirstName);
 @Html.DisplayFor(m => m.LastName);
 @Html.DisplayFor(m => m.Age)
 @Html.DisplayFor(m => m.PhoneNumbers)

Note that I that I did NOT have to use a foreach.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top