I have a strongly typed view where I have a form based on a Model Contact. In the textboxes, the default values are those of the contact that I'm passing to the view in the controller. So I have a class Contact as follows:
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;
}
}
There is a list of FonctionContact. The class of FonctionContact:
public class FonctionContact
{
public int IdFonction;
public string LibelleFonction;
public FonctionContact() { }
public FonctionContact(int idFonction, string libelleFonction)
{
this.IdFonction = idFonction;
this.LibelleFonction = libelleFonction;
}
}
So I would like to display the property ListeFonctions of the Contact in a listBoxfor but it doesn't work. There is my form where I've tried to display the list :
@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"));
}
It shows me an error: "Model.FonctionContact doesn't have a property IdFonction. So I'm stuck here, I can't find out what's wrong. Somebody has an idea ?
Basically, you'll need to provide the ListBoxFor with a list of value items (integers, which you could use to load some previously selected and saved items). Also, it will need a MultiSelectList as the second parameter (for the previously explained reason, because it's not a DropDownList with just one selected item), which would probably be neater to compose in the model, as I have written below:
Model
inside the view's form