代码正在运行,但我没有收到错误消息:
没有具有键“Register.CountryId”的“IEnumerable”类型的 ViewData 项
鉴于:
@using (Html.BeginForm((string)ViewBag.FormAction, "NMPAccount", new { @id = "myForm", @name = "myForm" }))
@Html.LabelFor(m => m.Register.CountryId)
@Html.DropDownListFor(m => m.Register.CountryId, Model.Register.CountryList,
new { @id = "CountryList" })
@Html.ValidationMessageFor(m => m.Register.CountryId)
}
在控制器中:
[AllowAnonymous]
public ActionResult Register() {
var registerViewModel = new RegisterViewModel();
registerViewModel.Initalize();
return View("Register", registerViewModel);
}
[AllowAnonymous]
[HttpPost]
public ActionResult Register(RegisterViewModel model) {
if (!ModelState.IsValid) {
model.Initalize();
ModelState.AddModelError(string.Empty, "");
return View("Register", model);
}
if (ModelState.IsValid && model.Register != null) {
if (RegisterViewModel.RegisterNewUser(model.Register))
return RedirectToAction("RegisterSuccess");
else
ModelState.AddModelError("", NMPAccountResource.Failed);
}
在视图模型中:
public class RegisterViewModel {
public RegisterViewModel() {
Register = new RegisterModel();
}
public RegisterModel Register { get; set; }
public void Initalize() {
var registerUser = new RegisterUser();
IList<CountryCodes> couList = Utilities.GetCountryList(languageId);
var countryList = (from data in couList
select new CustomItem() {
Id = data.CountryCodesId,
Description = data.CountryName
}).ToList();
if (countryList.Count > 0) {
countryList[0].Id = null;
}
var clist = new SelectList(countryList, "Id", "Description");
Register.CountryList = clist;
}
**注册型号**:
public string CountryId { get; set; }
public IEnumerable<SelectListItem> CountryList { get; set; }
我想从“视图模型”中做到这一点。
我搜索了StackOverflow,但没有找到解决问题的答案。