ASP.NET MVC“ SelectListItem”没有键定义的错误

时间:2018-11-22 18:29:40

标签: c# asp.net asp.net-mvc

我正在使用ASP.NET 个人用户帐户实施,并尝试在“注册”视图中添加一个DropDownList,以便用户可以选择他所在的城市。我收到以下错误:  'SelectListItem'没有定义键。定义此EntityType的键。 SelectListItems:EntityType:EntitySet'SelectListItems'基于未定义键的'SelectListItem'类型。

RegisterViewModel 中,我添加了以下内容:

  [Required(ErrorMessage = "Select City!")]
  [Display(Name = "City")]
  public int CityId { get; set; }
  public List<SelectListItem> Cities { get; set; }

查看

<div class="form-group">
     @Html.LabelFor(m => m.CityId, new { @class = "col-md-2 control-label" })
     <div class="col-md-10">
            @Html.DropDownList("CityId", Model.Cities, "Select city", new { @class = "form-control" })
     </div>
</div>

控制器:

获取方法:

public ActionResult Register()
 {
        var model = new RegisterViewModel();
        model.Cities = new List<SelectListItem>();
        SqlConnection con = //here is the connection string;
        string query = "SELECT * FROM City";
        con.Open();
        try
        {
            SqlCommand com = new SqlCommand(query, con);
            SqlDataReader reader = com.ExecuteReader();
            while (reader.Read())
                {  
                   var city = new SelectListItem { Text = reader["Name"].ToString(), Value = reader["Id"].ToString() };
                   model.Cities.Add(city);
                }
            }
            catch(Exception ex)
            {
                Response.Write("Eroare baza de date" + ex.Message);
            }
            finally
            {
                con.Close();
            }

            return View(model);
}

最后, POST 方法

public async Task<ActionResult> Register(RegisterViewModel model)
        {
            if (ModelState.IsValid)
            {
               model.Cities = new List<SelectListItem>();
               int  cityId = model.CityId;
               var user = new ApplicationUser 
                    { UserName = model.UserName, Email = model.Email, CityId = cityId};
                var result = await UserManager.CreateAsync(user, model.Password);
                if (result.Succeeded)
                {
                    await SignInManager.SignInAsync(user, isPersistent:false, rememberBrowser:false);

                    return RedirectToAction("Index", "Home");
                }
                AddErrors(result);
            }

            return View(model);
        }

1 个答案:

答案 0 :(得分:0)

尝试使用此

@Html.DropDownListFor(x=>x.CityId, Model.Cities, "Select city", new { @class = "form-control" })

代替此

@Html.DropDownList("CityId", Model.Cities, "Select city", new { @class = "form-control"})