MVC EditorFor bind to type in array

Posted by BradBrening on Stack Overflow See other posts from Stack Overflow or by BradBrening
Published on 2011-11-25T01:42:40Z Indexed on 2011/11/25 1:51 UTC
Read the original article Hit count: 234

Filed under:
|
|

I have a ViewModel that, among other properties, contains an array of 'EmailAddress' objects. EmailAddress itself has properties such as "Address", and "IsPrimary". My view model breakdown is:

public class UserDetailsViewModel {
  public BUser User { get; set; }
  public string[] Roles { get; set; }
  public EmailAddress[] EmailAddresses { get; set; }
}

I am showing a "User Details" page that is pretty standard. For example, I'm displaying data using @Html.DisplayFor(model => model.User.UserName) and @Html.DisplayFor(model => model.User.Comment) I also have a section on the page that lists all of the EmailAddress objects associated with the user:

@if(Model.EmailAddresses.Length > 0) {
  foreach (var address in Model.EmailAddresses) {
    <div>
      @Html.DisplayFor(model => address.Address)
    </div>
  }
} else {
  <div class="center">User does not have any email addresses.</div>
}

My problem is that I would like to show an "Add Email Address" form above the list of email addresses. I thought I would take the "normal" approach thusly:

@using(Html.BeginForm(new { id=Model.User.UserName, action="AddUserEmailAddress" })) {    
  <text>Address:</text> @Html.EditorFor(model => ** HERE I AM STUCK **)
  <input type="submit" value="Add Email" class="button" />
}

As you may be able to tell, I am stuck here. I've tried model => Model.EmailAddresses[0] and model => Model.EmailAddresses.FirstOrDefault(). Both of these have failed horribly.

I am sure that I am going about this all wrong. I've even thought of adding a "dummy" property to my ViewModel of type EmailAddress just so that I can bind to that in my EditorFor - but that seems to be a really bad hack. There has to be something simple that I'm overlooking!

I would appreciate any help anyone can offer with this matter. Thank you in advance!

© Stack Overflow or respective owner

Related posts about asp.net-mvc-3

Related posts about binding