2013-08-08 2 views
0

У меня есть строго типизированный вид, где у меня есть форма, основанная на контакте модели. В текстовых полях значениями по умолчанию являются значения контакта, которые я передаю в представление в контроллере. Поэтому у меня есть класс контакт следующим образом:Как заполнить ListBox на основе списка модели в asp.net mvc4?

public class Contact 
    { 
     public int IdContact { get; set; } 
     public string Nom { get; set; } 
     public string Prenom { get; set; } 
     public string Email { get; set; } 
     public string Fonction { get; set; } 
     public List<FonctionContact> ListeFonctions = new List<FonctionContact>(); 
     public string TelephoneFixe { get; set; } 
     public string TelephonePort { get; set; } 
     public Contact() { } 

     public Contact(int idContact, string nom, string prenom, string email, string telephoneFixe, string telephonePort) 
     { 
      this.IdContact = idContact; 
      this.Nom = nom; 
      this.Prenom = prenom; 
      this.Email = email; 
      this.TelephoneFixe = telephoneFixe; 
      this.TelephonePort = telephonePort; 
     } 

     public Contact(int idContact, string nom, string prenom, List<FonctionContact> listeFonctions, string email, string telephoneFixe, string telephonePort) 
     { 
      this.IdContact = idContact; 
      this.Nom = nom; 
      this.Prenom = prenom; 
      this.ListeFonctions = listeFonctions; 
      this.Email = email; 
      this.TelephoneFixe = telephoneFixe; 
      this.TelephonePort = telephonePort; 
     } 
    } 

Существует список FonctionContact. Класс FonctionContact:

public class FonctionContact 
{ 
    public int IdFonction; 
    public string LibelleFonction; 

    public FonctionContact() { } 

    public FonctionContact(int idFonction, string libelleFonction) 
    { 
     this.IdFonction = idFonction; 
     this.LibelleFonction = libelleFonction; 
    } 
} 

Так что я хотел бы, чтобы отобразить в отель за ListeFonctions из Контакта в listBoxfor, но он не работает. Существует моя форма, в которой я попытался отобразить список:

@using (Html.BeginForm()){ 
    <label>Nom:</label> 
    @Html.TextBoxFor(contact => contact.Nom, new { @Value = @Model.Nom }) 
    <label>Prénom:</label> 
    @Html.TextBoxFor(contact => contact.Prenom, new { @Value = @Model.Prenom }) 
    ///the next controls for the next properties of class Contact... 
    <label>Fonction(s):</label> 
    @Html.ListBoxFor(contact => contact.ListeFonctions, new SelectList(Model.ListeFonctions, "IdFonction", "LibelleFonction")); 
    } 

Он показывает мне ошибку:. «Model.FonctionContact не имеет свойство IdFonction Так что я застрял здесь, я не могу узнать, что случилось. У кого-то есть идея?

ответ

1

В принципе, вам нужно предоставить ListBoxFor список значений (целые числа, которые можно использовать для загрузки ранее выбранных и сохраненных элементов). потребуется второй MultiSelectList в качестве второго параметра (по ранее объясненной причине, потому что это не DropDownList с одним выбранным элементом), который, вероятно, будет более аккуратным для компоновки в модели, как я уже писал ниже:

Модель

public class Contact 
     { 
      public int IdContact { get; set; } 
      public string Nom { get; set; } 
      public string Prenom { get; set; } 
      public string Email { get; set; } 
      public string Fonction { get; set; } 

      // you could save a selection of items from that list 
      private List<int> _selectedFonctionIds;   
      public List<int> SelectedFonctionIds{ 
       get { 
        return _selectedFonctionIds?? new List<int>(); 
       } 
       set { 
        _selectedFonctionIds= value; 
       } 
      } 
      private List<FonctionContact> _listeFonctions; 
      public MultiSelectList ListeFonctions{ 
       get { 
        return new MultiSelectList(
          _listeFonctions, 
          "IdFonction", // dataValueField 
          "LibelleFonction" // dataTextField 
       ); 
        } 
      } 
      public string TelephoneFixe { get; set; } 
      public string TelephonePort { get; set; } 
      public Contact() { } 

      public Contact(int idContact, string nom, string prenom, string email, string telephoneFixe, string telephonePort) 
      { 
       this.IdContact = idContact; 
       this.Nom = nom; 
       this.Prenom = prenom; 
       this.Email = email; 
       this.TelephoneFixe = telephoneFixe; 
       this.TelephonePort = telephonePort; 
      } 

      public Contact(int idContact, string nom, string prenom, List<int> selectedFonctionIds, List<FonctionContact> listeFonctions, string email, string telephoneFixe, string telephonePort) 
      { 
       this.IdContact = idContact; 
       this.Nom = nom; 
       this.Prenom = prenom; 
       this.SelectedFonctionIds = selectedFonctionIds; 
       this._listeFonctions = listeFonctions; 
       this.Email = email; 
       this.TelephoneFixe = telephoneFixe; 
       this.TelephonePort = telephonePort; 
      } 
     } 

в форме отображения вида

@Html.ListBoxFor(contact => contact.SelectedFonctionIds, Model.ListeFonctions) 
+0

Я пытался, но он показывает мне ошибку Databinding о том, что класс FonctionContact не имеет такое свойство, как IdFonction –

+0

У вас попытался сделать IdFonction одним из свойств ('public int IdFonction {get; задавать; } 'вместо простого' public int IdFonction; ')? То же самое должно быть сделано и для LibelleFonction. –

+0

... никогда не работайте, когда устали! это работает!, спасибо большое @Mark –