2013-08-21 26 views
5

Sto lavorando con ASP.NET MVC4 e ora voglio aggiungere un elenco a discesa con i dati dal mio database mysql. Questo è quello che faccio:Il valore non può essere nullo. Nome parametro: elementi (DrodownList)

A mio vista (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> 

Nel mio 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); 
} 

ricevo i Distretti da my Repository come questo:

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

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

DropDownList è riempito con i distretti, ma quando clicco su "Registrati" ottengo questo errore:

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

Quando il debug del metodo vedo che il ModelState è Non valido.
Key 11 è DistrictID e comprende la districtid ma Key 12 è Distretti e dà l'errore: "The district field is required" ...

Che cosa sto facendo di sbagliato?

+0

L'eccezione viene generata solo quando la convalida non riesce o quando viene inoltrata anche la convalida? – Andrei

risposta

6

Considerare il caso in cui la convalida del modello fallisce. La vista verrà nuovamente visualizzata di nuovo con il modello inviato con la richiesta. Tuttavia questa linea:

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

avrà null come primo parametro, in quanto ViewBag.Districts non fu ripopolata, causando l'eccezione. Quindi, al fine di evitare eccezione solo impostare nuovamente questa proprietà:

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

Update. Quando si visualizza la definizione del modello, la cosa che viene immediatamente in mente è l'attributo Required della raccolta Districts. Molto probabilmente non è necessario che l'utente inserisca nessuno di questi, né li si salva nel database. Prova a rimuovere questo attributo e l'errore relativo a questa proprietà scompare.

+0

Ora, quando clicco su "Registrati", si ricarica la pagina e i valori sono ancora compilati ma non succede nulla ... Inoltre non l'ho aggiunto al database – nielsv

+0

@ niels123, hai provato il debug? Almeno quello che puoi fare è usare una chiave significativa invece della stringa vuota per "AddModelError" e visualizzarla da qualche parte sulla pagina con Html.ValidationMessage - questo mostrerà se si verifica l'eccezione. Ma ancora, il modo migliore per capire cosa va storto è solo il debug del metodo. – Andrei

+0

Ho controllato il metodo e lo stato del modello non è valido. La chiave 11 (DistrictID) ha il valore del mio distretto, ma la chiave 12 (distretti) dà un errore: "Il campo distrettuale è richiesto". – nielsv

Problemi correlati