Dropdownlist无法设置字符串(MVC) [英] Dropdownlistfor unable to set on string (MVC)

查看:73
本文介绍了Dropdownlist无法设置字符串(MVC)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Hello People,

我有这个问题:

我想把婚姻状况放在下拉列表中,当我为新用户注册时,选择已婚或未婚,并点击保存按钮,在我的数据库上我看到它收到了ID(1,2)而不是已婚或未婚。

这就是我所看到的在我的数据库上:

查看图片





我错过了什么? 





我的尝试:



在我的文件夹帐户 - > AccountViewModels.cs 我把这些代码:

公共类RegisterViewModel 
{
[必需]
[显示(姓名=Etat civil)]
[范围(1,2,ErrorMessage =Veuillez choisir)]
public string Civilite {get;组;
}
公共类EtatCivil
{
public int Id {get;组; }
public string Libelle {get;组; }
}





控制器 - > 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();
}





 // 
// POST:/ Account / Register
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async任务< ActionResult>注册(RegisterViewModel模型)
{
if(!ModelState.IsValid)返回View(模型);
var user = new ApplicationUser(){UserName = model.UserName};
var result = await UserManager.CreateAsync(user,model.Password);
if(result.Succeeded)
{
try {
// ajout du user dans la table client
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(例外){
// await UserManager.DeleteAsync(user);
ModelState.AddModelError(,Echeccréationclient,veuillezréessayer);
return View(model);
}
//在affecte lerôle客户端上
UserManager.AddToRole(user.Id,client);
等待SignInAsync(user,isPersistent:false);
返回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);

//如果我们到目前为止,有些事情失败,重新显示形式
返回View(模型);
}





在我的观看次数 - > 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>

解决方案

这是下拉菜单的工作方式,有两个元素,名称和值。名称出现在列表中,值是随表单提交的内容。通常,您需要时将ID转换回相关文本。但是,如果您确实只想要文本而不关心ID,那么请将值和名称都设置为所需的文本。但是我怀疑那不是你真正想要做的。


非常感谢 F-ES Sitecore 的帮助!



实际上我所做的是:

 // 
// POST:/账户/注册
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task< ActionResult>注册(RegisterViewModel模型)
{
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);
if(!ModelState.IsValid)返回View(模型);
var user = new ApplicationUser(){UserName = model.UserName};
var result = await UserManager.CreateAsync(user,model.Password);
if(result.Succeeded)
{
try {
// ajout du user dans la table client
using(var dal = new DALEF.WebShopEntities())
{

dal.Client.Add(
new DALEF.Client
{
CLI_Nom = model.Nom,
CLI_Prenom = model。 Prenom,
CLI_Civilite = lstEtat.Find(x => x.Id == int.Parse(model.Civilite))。Libelle,
CLI_Email = model.Email,
CLI_Adresse = model.Adresse,
CLI_CodePostal = model.CodePostal,
CLI_Ville = model.Ville,
CLI_Telephone = model.Telephone,
CLI_A spUser_Id = user.Id
});
dal.SaveChanges();
}

}
catch(例外){
// await UserManager.DeleteAsync(user);
ModelState.AddModelError(,Echeccréationclient,veuillezréessayer);
return View(model);
}
//在affecte lerôle客户端上
UserManager.AddToRole(user.Id,client);
等待SignInAsync(user,isPersistent:false);
返回RedirectToAction(Index,Home);
}



AddErrors(result);

//如果我们到目前为止,有些事情失败,重新显示形式
返回View(模型);
}





它有效,我可以在我的数据库上看到字符串的状态而不是int。 :)


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

//  
        // GET: /Account/Register  
        [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();  
        }  



//  
        // POST: /Account/Register  
        [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 {  
                    // ajout du user dans la table client  
                    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) {                         
                    //await UserManager.DeleteAsync(user);  
                    ModelState.AddModelError("", "Echec création client, veuillez réessayer");  
                    return View(model);  
                }  
                // on affecte le rôle client  
                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);  
  
            // If we got this far, something failed, redisplay form  
            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> 

解决方案

That's how dropdowns work, there are two elements, the name and the value. The name is what appears in the list and the value is what is submitted with the form. Normally you'd convert the ID back to the relevant text when needed. However if you really do only want the text and you don't care about the ID then make both the value and name the text you want. However I suspect that's not what you really want to do.


Many thanks to F-ES Sitecore for your help!

Actually what I have done is this:

//
        // POST: /Account/Register
        [HttpPost]
        [AllowAnonymous]
        [ValidateAntiForgeryToken]
        public async Task<ActionResult> Register(RegisterViewModel model)
        {
            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");
            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 {
                    // ajout du user dans la table client
                    using (var dal = new DALEF.WebShopEntities())
                    {

                        dal.Client.Add(
                            new DALEF.Client
                            {
                                CLI_Nom = model.Nom,
                                CLI_Prenom = model.Prenom,
                                CLI_Civilite = lstEtat.Find(x=>x.Id == int.Parse(model.Civilite)).Libelle,
                                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) {                       
                    //await UserManager.DeleteAsync(user);
                    ModelState.AddModelError("", "Echec création client, veuillez réessayer");
                    return View(model);
                }
                // on affecte le rôle client
                UserManager.AddToRole(user.Id, "client");
                await SignInAsync(user, isPersistent: false);
                return RedirectToAction("Index", "Home");
            }

            

            AddErrors(result);

            // If we got this far, something failed, redisplay form
            return View(model);
        }



An it works, I can see on my db the status on string and not on int. :)


这篇关于Dropdownlist无法设置字符串(MVC)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆