2013-08-21 26 views
5

私はASP.NET MVC4で作業しています。今、私のmysqlデータベースのデータをドロップダウンリストに追加したいと思います。これは私が何をすべきかです:値はnullにはできません。パラメータ名:items(DrodownList)

ビュー(Register.cshtml)では:私のコントローラ(AccountController)では `

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

[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から地区を取得します私のリポジトリはこのようになります:

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

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

ドロップダウンリストには、地区で満たされているが、私はこのエラーを取得する「登録」をクリックしたとき:

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

私はにModelStateがあることを確認する方法をデバッグするとき有効ではありません。
キー11はDistrictIDですが、districtidを含みますが、キー12は地区です。"The district field is required" ...

私は間違っていますか?

+0

検証が失敗した場合、または検証が成功した場合にのみ例外がスローされます。 – Andrei

答えて

6

モデルの検証に失敗した場合を考えてください。リクエストとともに送信されたモデルでビューが再度表示されます。しかし、この行:ViewBag.Districtsは例外を発生させ、再作成されなかったので、

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

は、最初のパラメータとしてnullを持つことになります。だから、例外を回避するために、もう一度、このプロパティを設定します。

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

更新。モデル定義を見ると、すぐに気になるのは、属性のDistrictsコレクションです。ほとんどの場合、ユーザーはそれらのいずれかを入力する必要はなく、データベースに保存することもありません。この属性を削除してみると、このプロパティに関するエラーは表示されなくなります。

+0

今、「登録」をクリックするとページがリロードされ、値はまだ入力されていますが、何も起こりません...データベースに追加されませんでした – nielsv

+0

@ niels123、デバッグを試しましたか?あなたができることは少なくとも、AddModelErrorに空の文字列の代わりに意味のあるキーを使用し、Html.ValidationMessageでページのどこかに表示することです。例外が発生した場合に表示されます。しかし、何が問題になるのかを理解する最良の方法は、メソッドをデバッグすることです。 – Andrei

+0

メソッドをチェックしましたが、モデルステートは無効です。キー11(地区ID)は私のdistrictidの値を持っていますが、キー12(地区)は「地区のフィールドは必須です」というエラーが表示されます。 – nielsv

関連する問題