我在 View 中填充 DropDownList 并在 POST 上收到此错误。
错误:没有具有键“SelectedCityName”的“IEnumerable”类型的 ViewData 项。
控制器:
public ViewResult Register()
{
var Cities = ILocaRepo.Cities.ToList();
var Wards = ILocaRepo.Wards.ToList() ;
var model = new RegisterViewModel
{
City = Cities.Select(x => new SelectListItem
{
Value = x.CityID.ToString(),
Text = x.CityName
}),
Ward = Wards.Select(x => new SelectListItem
{
Value = x.WardID.ToString(),
Text = x.WardName
})
};
return View(model);
}
//
// POST: /Account/Register
[HttpPost]
public ActionResult Register(RegisterViewModel model)
{
if (ModelState.IsValid)
{
// Attempt to register the user
try
{
MembershipService.CreateUser(model.User.Username, model.User.Password, model.User.Name, model.SelectedCityName, model.SelectedWardName, model.User.Address, model.User.Phone, model.User.Email, "Member");
FormsAuthentication.SetAuthCookie(model.User.Username, false);
return RedirectToAction("ListProduct", "Product");
}
catch (ArgumentException ae)
{
ModelState.AddModelError("", ae.Message);
}
}
// If we got this far, something failed, redisplay form
return View(model);
}
看法 :
<tr>
<td class="info_label">City</td>
<td>@Html.DropDownListFor(m=>m.SelectedCityName,Model.City,"-- Chọn thành phố --",new { @class = "dropdown" })</td>
</tr>
<tr>
<td class="info_label">Ward</td>
<td>@Html.DropDownListFor(m => m.SelectedWardName, Model.Ward, "-- Chọn quận --", new { @class = "dropdown" })</td>
</tr>
和视图模型:
public User User { get; set; }
public string SelectedCityName { get; set; }
public string SelectedWardName { get; set; }
public IEnumerable<SelectListItem> City { get; set; }
public IEnumerable<SelectListItem> Ward { get; set; }
如何让 SelectedCityName 作为 RegisterUser 方法的参数传递?任何帮助表示赞赏。