gpt4 book ai didi

c# - 没有具有键 'IEnumerable' 的 'Register.CountryId' 类型的 ViewData 项

转载 作者:太空宇宙 更新时间:2023-11-03 10:40:35 24 4
gpt4 key购买 nike

代码运行正常,但我没有收到错误:

There is no ViewData item of type 'IEnumerable' that has the key 'Register.CountryId'

可见:

 @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)

}

在 Controller 中:

[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);

}

在 ViewModel 中:

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; }

我想从“ View 模型”执行此操作。

我搜索了 StackOverflow,但没有找到解决我问题的答案。

最佳答案

我无法将其添加为评论,但您需要在 Register 操作的 POST 版本中返回一个 View 模型

    [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);
//there needs to be code here to return the view.
return View("Register", model); //<--- this is missing
}

}
//there needs to be code here to return the view.
return View("Register", model); //<--- this is missing

}

如果条件 !ModelState.IsValidTRUE,您的代码之前可能一直有效。也许您没有通过此检查,下面的代码在运行时失败。

关于c# - 没有具有键 'IEnumerable<SelectListItem>' 的 'Register.CountryId' 类型的 ViewData 项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25482056/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com