【发布时间】:2018-11-23 14:30:42
【问题描述】:
我正在使用 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>
控制器:
GET方法:
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);
}
【问题讨论】:
-
您的代码看起来不错。你什么时候收到错误?当你加载页面? (获取操作)?
-
填写完表格并按下提交按钮后
-
如果
ModelState.IsValid返回false,你需要重新加载model.Cities集合,然后才能返回到同一个视图(它使用这个集合来构建SELECT元素)。 -
我发现了错误,在 ApplicationUser 类的 IdentityModels 中我添加了“public List
Cities { get; set; }”,这是不正确的 -
这就是你使用视图模型的原因:)
标签: c# asp.net asp.net-mvc