2013-08-21 26 views
5

Pracuję z ASP.NET MVC4 i teraz chcę dodać dropdownlist z danymi z mojej bazy danych mysql. To co mam zrobić:Wartość nie może być pusta. Nazwa parametru: items (DrodownList)

W moim widzenia (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> 

W moim 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); 
} 

dostaję od Dzielnice moje Repozytorium w ten sposób:

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

Moja 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 jest wypełniona dzielnicach ale gdy klikam na „Register” otrzymuję ten błąd:

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

Kiedy debugowania metody widzę, że ModelState jest Nieważny.
Klucz 11 jest DistrictID i obejmuje districtid, ale klucz 12 to Districts i podaje błąd: "The district field is required" ...

Co robię źle?

+0

Wyjątek jest zgłaszany tylko w przypadku niepowodzenia sprawdzania poprawności lub sprawdzania poprawności? – Andrei

Odpowiedz

6

Rozważ przypadek, gdy weryfikacja modelu zakończy się niepowodzeniem. Widok zostanie ponownie wyświetlony w przypadku modelu wysłanego wraz z żądaniem. Jednak ta linia:

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

będzie miał null jako pierwszy parametr, gdyż ViewBag.Districts nie zostało odbudowane, powodując wyjątku. Tak więc w celu uniknięcia wyjątek tylko ponownie ustawić tę właściwość:

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

Update. Po obejrzeniu definicji modelu rzeczą, która natychmiast przychodzi do głowy, jest atrybut Required z kolekcji Districts. Najprawdopodobniej nie potrzebujesz użytkownika, aby wprowadzić którykolwiek z nich, ani zapisać go w bazie danych. Spróbuj usunąć ten atrybut, a błąd dotyczący tej właściwości zniknie.

+0

Teraz, gdy klikam na "Register", po prostu ponownie załaduje stronę i wartości są nadal wypełnione, ale nic się nie dzieje ... Również nie dodałem go do bazy danych – nielsv

+0

@ niels123, czy próbowałeś debugowania? Przynajmniej możesz użyć jakiegoś znaczącego klucza zamiast pustego łańcucha dla 'AddModelError' i wyświetlić go gdzieś na stronie z Html.ValidationMessage - to pokaże, jeśli wystąpi wyjątek. Jednak najlepszym sposobem na zrozumienie, co idzie nie tak, jest debugowanie metody. – Andrei

+0

Sprawdziłem metodę, a stan modelu jest niepoprawny. Klucz 11 (DistrictID) ma wartość mojego districtid, ale Key 12 (Districts) podaje błąd: "Pole dystryktu jest wymagane". – nielsv