(Html.DropdownList) 值不能为空.参数名称:项



我有一个登录视图页面,其中包含 2 个部分视图_LoginPartial_RegisterPartial。在_RegisterPartial中,我有包含角色的下拉列表。

@Html.DropDownListFor(m => m.CompanyProfile, new SelectList(ViewBag.CompanyProfiles, "AccountId", "AccountName"), "Select", new { @class = "form-control" })

我在 GET 方法中将此下拉列表初始化为

//
// GET: /Account/Login
[AllowAnonymous]
public ActionResult Login(string returnUrl)
{
ViewBag.CompanyProfiles = util.GetCompanyProfiles();
ViewBag.ReturnUrl = returnUrl;
return View();
}

我从数据库获取列表的代码是

public List<abo_AccountType> GetCompanyProfiles()
{
List<abo_AccountType> companyProfiles = new List<abo_AccountType>();
companyProfiles = db.GetAccountTypes().ToList();
return companyProfiles;
}

当我们打开登录页面时,列表被初始化,我知道我需要在 POST 方法中再次初始化下拉列表,所以我这样做就像我在 GET 方法中所做的那样

//
// POST: /Account/Register
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult Register(RegisterViewModel model)
{
ViewBag.CompanyProfiles = util.GetCompanyProfiles();
if (ModelState.IsValid)
{
ViewBag.CompanyProfiles = util.GetCompanyProfiles();
string[] errors = util.CheckDuplicateAccount(model);
if (errors == null)
{
long currentUser = Convert.ToInt64(System.Web.HttpContext.Current.User.Identity.GetUserId());
util.CreateNewAccount(model, currentUser);
}
else
{
AddErrors(errors);
}
}
return RedirectToAction("Login");
}

即使我再次初始化下拉列表,我仍然收到Value cannot be null. Parameter name: items的错误。 我已经搜索了SO上的几乎所有答案,他们都说我需要再次初始化下拉列表,我正在这样做,那么为什么我仍然收到此错误。

您应该为注册生成"GET"方法,并在其中设置公司配置文件。

[HttpGet]
[AllowAnonymous]
public ActionResult Register()
{
ViewBag.CompanyProfiles = util.GetCompanyProfiles();
return View();
}

创建另一个同时具有这两个模型属性的模型,并在后期操作中传递它。

[HttpGet]
[AllowAnonymous]
public ActionResult Register(combinedModel model)
{
ViewBag.CompanyProfiles = util.GetCompanyProfiles();
return View(model);
}

最新更新