Hello People,
I have this issue:
I want to put the marital status on drop down list, when I make the register of the new user, and chose married or unmarried, and click on the save button, on my db i see that it received the id (1, 2) instead of "married" or "unmarried".
This is what I see on my db:
See image
What am I missing?
What I have tried:
On my Folder
Account ->
AccountViewModels.cs I put these codes:
public class RegisterViewModel
{
[Required]
[Display(Name = "Etat civil")]
[Range(1, 2, ErrorMessage = "Veuillez choisir")]
public string Civilite { get; set;
}
public class EtatCivil
{
public int Id { get; set; }
public string Libelle { get; set; }
}
and on
Controllers ->
AccountController.cs
[AllowAnonymous]
public ActionResult Register()
{
var lstEtat = new List<EtatCivil>
{
new EtatCivil {Id = 0, Libelle = "vide"},
new EtatCivil {Id = 1, Libelle = "Célibataire"},
new EtatCivil {Id = 2, Libelle = "Marié"}
};
ViewBag.ListEtatCivil = new SelectList(lstEtat, "Id", "Libelle");
return View();
}
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Register(RegisterViewModel model)
{
if (!ModelState.IsValid) return View(model);
var user = new ApplicationUser() { UserName = model.UserName };
var result = await UserManager.CreateAsync(user, model.Password);
if (result.Succeeded)
{
try {
using (var dal = new DALEF.WebShopEntities())
{
dal.Client.Add(
new DALEF.Client
{
CLI_Nom = model.Nom,
CLI_Prenom = model.Prenom,
CLI_Civilite = model.Civilite,
CLI_Email = model.Email,
CLI_Adresse = model.Adresse,
CLI_CodePostal = model.CodePostal,
CLI_Ville = model.Ville,
CLI_Telephone = model.Telephone,
CLI_AspUser_Id = user.Id
});
dal.SaveChanges();
}
}
catch(Exception) {
ModelState.AddModelError("", "Echec création client, veuillez réessayer");
return View(model);
}
UserManager.AddToRole(user.Id, "client");
await SignInAsync(user, isPersistent: false);
return RedirectToAction("Index", "Home");
}
var lstEtat = new List<EtatCivil>
{
new EtatCivil {Id = 0, Libelle = "vide"},
new EtatCivil {Id = 1, Libelle = "Célibataire"},
new EtatCivil {Id = 2, Libelle = "Marié"}
};
ViewBag.ListEtatCivil = new SelectList(lstEtat, "Id", "Libelle");
AddErrors(result);
return View(model);
}
On my
Views -->
Register.cshtml
<div class="form-group">
@Html.LabelFor(m => m.Civilite, new { @class = "col-md-2 control-label" })
<div class="col-md-10">
@Html.DropDownListFor(m => m.Civilite, (SelectList)ViewBag.ListEtatCivil)
</div>