值不能为空.参数名称:items (DrodownList) [英] Value cannot be null. Parameter name: items (DrodownList)

查看:40
本文介绍了值不能为空.参数名称:items (DrodownList)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 ASP.NET MVC4,现在我想添加一个下拉列表,其中包含来自我的 mysql 数据库的数据.这就是我所做的:

在我的视图(Register.cshtml)中:`

@Html.LabelFor(m => m.DistrictID, new { @class="control-label"})<div class="控件">@Html.DropDownListFor(model => model.DistrictID, new SelectList(ViewBag.Districts, "district_id", "district_name", Model.DistrictID))

在我的控制器(AccountController)中:

[AllowAnonymous]公共操作结果寄存器(){var Districts = repository.GetDistricts();ViewBag.Districts = 地区;返回视图(新注册模型());}////POST:/账户/注册[HttpPost][允许匿名][验证AntiForgeryToken]公共 ActionResult 注册(注册模型模型){如果(模型状态.IsValid){//尝试注册用户尝试{MembershipService.CreateUser(model.Name,model.FamilyName,model.BirthDate,model.Sex,model.Nationality,model.Email,model.UserName,model.Password,model.Street,model.StreetNr);FormsAuthentication.SetAuthCookie(model.UserName, false);return RedirectToAction("Index", "Home");}catch (ArgumentException ae){ModelState.AddModelError("", ae.Message);}}//如果我们到了这一步,有些事情失败了,重新显示表单返回视图(模型);}

我像这样从我的存储库获取区:

 public IQueryable获取分区(){从entities.districts 中的地区返回orderby District.district_name选择地区;}

我的注册模型:

公共类RegisterModel{[必需的][显示(名称=名字")]公共字符串名称 { 获取;放;}[必需的][Display(Name = "Family name")]公共字符串 FamilyName { 获取;放;}[必需的][显示(姓名=生日")]公共日期时间出生日期 { 获取;放;}[必需的][显示(名称=性别")]公共字符串性{得到;放;}[必需的][显示(姓名=国籍")]公共字符串国籍{得到;放;}[必需的][显示(姓名=电子邮件")]公共字符串电子邮件{获取;放;}[必需的][Display(Name = "用户名")]公共字符串用户名 { 获取;放;}[必需的][StringLength(100, ErrorMessage = "{0} 必须至少有 {2} 个字符长.", MinimumLength = 6)][数据类型(数据类型.密码)][显示(名称=密码")]公共字符串密码{获取;放;}[数据类型(数据类型.密码)][Display(Name = "确认密码")][Compare("Password", ErrorMessage = "密码和确认密码不匹配.")]公共字符串 ConfirmPassword { get;放;}[必需的][显示(名称=街道")]公共字符串街{得到;放;}[必需的][显示(名称=街道号码")]公共 int StreetNr { 得到;放;}[必需的][显示(名称=地区")]公共 IEnumerable区 { 得到;放;}公共 int DistrictID { 获取;放;}}

下拉列表中充满了地区,但当我点击注册"时,出现此错误:

<块引用>

值不能为空.参数名称:items

描述:执行过程中发生未处理的异常当前的网络请求.请查看堆栈跟踪以了解更多信息有关错误及其在代码中的来源的信息.

异常详细信息:System.ArgumentNullException:值不能为空.参数名称:items

当我调试该方法时,我发现 ModelState 无效.
键 11 是 DistrictID 并包含 DistrictID 但键 12 是 Districts 并给出错误:"The District field is required" ...

我做错了什么?

解决方案

考虑模型验证失败的情况.视图将与请求一起发送的模型再次重新显示.然而这一行:

new SelectList(ViewBag.Districts, "district_id", "district_name", Model.Districts)

null 作为第一个参数,因为 ViewBag.Districts 没有重新填充,导致异常.所以为了避免异常只需再次设置这个属性:

//如果我们走到这一步,有些事情失败了,重新显示表单var Districts = repository.GetDistricts();ViewBag.Districts = 地区;返回视图(模型);

更新.当看到模型定义时,立即想到的是Districts集合的Required属性.很可能您不需要用户输入任何这些内容,也不需要将它们保存到数据库中.尝试删除此属性,有关此属性的错误将消失.

I'm working with ASP.NET MVC4 and now I want to add a dropdownlist with data from my mysql database. This is what I do :

In my view (Register.cshtml):`

<div class="control-group">
    @Html.LabelFor(m => m.DistrictID, new { @class= "control-label"})
    <div class="controls">
        @Html.DropDownListFor(model => model.DistrictID, new SelectList(ViewBag.Districts, "district_id", "district_name", Model.DistrictID))
    </div>
</div>

In my Controller (AccountController):

[AllowAnonymous]
public ActionResult Register()
{
    var districts = repository.GetDistricts();
    ViewBag.Districts = districts;

    return View(new RegisterModel());
}

//
// POST: /Account/Register

[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult Register(RegisterModel model)
{

    if (ModelState.IsValid)
    {
        // Attempt to register the User
        try
        {
            MembershipService.CreateUser(model.Name, model.FamilyName, model.BirthDate, model.Sex, model.Nationality, model.Email, model.UserName, model.Password, model.Street, model.StreetNr);

            FormsAuthentication.SetAuthCookie(model.UserName, false);
            return RedirectToAction("Index", "Home");
        }
        catch (ArgumentException ae)
        {
            ModelState.AddModelError("", ae.Message);
        }
    }

    // If we got this far, something failed, redisplay form
    return View(model);
}

I get the Districts from my Repository like this:

 public IQueryable<district> GetDistricts()
 {
     return from district in entities.districts
            orderby district.district_name
            select district;
 }

My RegisterModel:

public class RegisterModel
{
    [Required]
    [Display(Name = "Given name")]
    public string Name { get; set; }

    [Required]
    [Display(Name = "Family name")]
    public string FamilyName { get; set; }

    [Required]
    [Display(Name = "Birthdate")]
    public DateTime BirthDate { get; set; }

    [Required]
    [Display(Name = "Sex")]
    public string Sex { get; set; }

    [Required]
    [Display(Name = "Nationality")]
    public string Nationality { get; set; }

    [Required]
    [Display(Name = "Email")]
    public string Email { get; set; }

    [Required]
    [Display(Name = "User name")]
    public string UserName { get; set; }

    [Required]
    [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
    [DataType(DataType.Password)]
    [Display(Name = "Password")]
    public string Password { get; set; }

    [DataType(DataType.Password)]
    [Display(Name = "Confirm password")]
    [Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
    public string ConfirmPassword { get; set; }

    [Required]
    [Display(Name = "Street")]
    public string Street { get; set; }

    [Required]
    [Display(Name = "Street Number")]
    public int StreetNr { get; set; }

    [Required]
    [Display(Name = "District")]
    public IEnumerable<SelectListItem> Districts { get; set; }

    public int DistrictID { get; set; }
}

The dropdownlist is filled with districts but when I click on "Register" I get this error:

Value cannot be null. Parameter name: items

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.ArgumentNullException: Value cannot be null. Parameter name: items

When I debug the method I see that the ModelState is NOT valid.
Key 11 is DistrictID and includes the districtid but Key 12 is Districts and gives the error: "The district field is required" ...

What am I doing wrong?

解决方案

Consider the case when model validation fails. View will be redisplayed again with model sent with the request. However this line:

new SelectList(ViewBag.Districts, "district_id", "district_name", Model.Districts)

will have null as a first parameter, since ViewBag.Districts was not repopulated, causing the exception. So in order to avoid exception just set this property again:

// If we got this far, something failed, redisplay form
var districts = repository.GetDistricts();
ViewBag.Districts = districts;
return View(model);

Update. When seeing the model definition, thing that immediately comes into the mind is Required attribute of the Districts collection. Most likely you do not need user to enter any of those, nor you save them into the database. Try removing this attribute, and error about this property will disappear.

这篇关于值不能为空.参数名称:items (DrodownList)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆