选择选定的值

时间:2019-03-30 10:01:50

标签: c# asp.net-mvc

我有一个带有一些值的下拉框。当用户选择一个值并单击保存时,我想在C#代码中获取该选定值。

这是我的代码:

 [HttpPost]
 public ActionResult AddAdmin(AdminViewModel model)
 {           
     if(ModelState.IsValid) 
     {
         List<Roles> list = col.Roles.ToList();
         model.Roles = col.Roles.ToList().Select(x => new SelectListItem()
         {
             Value = x.RoleName,
             Text = "Choose a role...",
         }).ToList();

         var admin = new Admin()
         {
             FirstName = model.FirstName,
             LastName = model.LastName,
             MemberEmail = model.MemberEmail,
             RoleName = list.Select(x => x.RoleName).ToString()
          };
          DBContext.Admin.Add(admin);
          DBContext.SaveChanges();
     }
     return View(model);
 }

所以我想要的是值:

Value = x.RoleName  (Let's just say the value is "Admin")

现在,我正试图像这样选择它:

RoleName = list.Select(x => x.RoleName).ToString()

但是我从数据库中得到的是这样:

System.Linq.Enumerable+WhereSelectListIterator`2[AuthSys.Models.Roles,System.String]

我在做什么错了?

2 个答案:

答案 0 :(得分:1)

我猜您想从字符串对象中返回与角色名称匹配的字符串

RoleName = list.FirstOrDefault(x => x.RoleName == "Admin")?.RoleName;

在您的视图中检查是否为null也是一个好主意,这样它就不会损坏

答案 1 :(得分:1)

[HttpPost]
public ActionResult AddAdmin(AdminViewModel model)
{           
   if(ModelState.IsValid) 
   {
      List<Roles> list = new List<Roles>(col.Roles.ToList());
      model.Roles = col.Roles.ToList().Select(x => new SelectListItem()
            {
                Value = x.RoleName,
                Text = "Choose a role...",

            }).ToList();

     var admin = new Admin()
     {
        FirstName = model.FirstName,
        LastName = model.LastName,
        MemberEmail = model.MemberEmail,
        //// If RoleName column is an type of VarChar then you are doing wrong here.
        // RoleName = list.Select(x => x.RoleName).ToString();

        //// try static string of role.
        RoleName = "Admin"
        or
        RoleName = list.FirstOrDefault(x => x.RoleName == model.[RoleNameFieldFromModel])?.RoleName;
     };

     DBContext.Admin.Add(admin);
     DBContext.SaveChanges();
   }
  return View(model);
}