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

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

问题描述

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

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 :

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

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>

在我的控制器(AccountController)中:

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

我的RegisterModel:

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:

值不能为null. 参数名称:项目

Value cannot be null. Parameter name: items

描述:执行以下操作时发生未处理的异常 当前的Web请求.请查看堆栈跟踪以获取更多信息 有关错误及其在代码中起源的信息.

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.

异常详细信息:System.ArgumentNullException:值不能为null. 参数名称:项目

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

当我调试方法时,我看到ModelState无效.
密钥11是DistrictID,并包括地区ID,但是密钥12是Districts,并给出错误:"The district field is required" ...

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" ...

我在做什么错了?

推荐答案

考虑模型验证失败的情况.随请求一起发送的模型将重新显示视图.但是这一行:

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)

将以null作为第一个参数,因为未重新填充ViewBag.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);

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

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.

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

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