2013-08-21 36 views
5

Tôi đang làm việc với ASP.NET MVC4 và bây giờ tôi muốn thêm một danh sách thả xuống với dữ liệu từ cơ sở dữ liệu mysql của tôi. Đây là những gì tôi làm:Giá trị không được rỗng. Tên tham số: items (DrodownList)

Trong quan điểm của tôi (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> 

Trong điều khiển của tôi (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); 
} 

tôi nhận được từ huyện của tôi Kho lưu trữ như thế này:

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

RegisterModel của tôi:

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

Các DropDownList được làm đầy với huyện nhưng khi tôi bấm vào "Đăng ký" Tôi nhận được lỗi này:

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

Khi tôi gỡ lỗi phương pháp này tôi thấy rằng ModelState là Không hợp lệ.
Khóa 11 là DistrictID và bao gồm quận nhưng Khóa 12 là Quận và đưa ra lỗi: "The district field is required" ...

Tôi đang làm gì sai?

+0

Ngoại lệ chỉ được ném khi xác thực không thành công hoặc khi quá trình xác thực được chuyển? – Andrei

Trả lời

6

Xem xét trường hợp khi xác thực mô hình không thành công. Chế độ xem sẽ được hiển thị lại với mô hình được gửi cùng với yêu cầu. Tuy nhiên dòng này:

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

sẽ có null như một tham số đầu tiên, kể từ khi ViewBag.Districts không repopulated, gây ra ngoại lệ. Vì vậy, để tránh ngoại lệ, chỉ cần đặt lại thuộc tính này:

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

Cập nhật. Khi xem định nghĩa mô hình, thứ ngay lập tức xuất hiện trong tâm trí là thuộc tính Required của bộ sưu tập Districts. Nhiều khả năng bạn không cần người dùng nhập bất kỳ thứ gì trong số đó, hoặc bạn cũng không lưu chúng vào cơ sở dữ liệu. Hãy thử xóa thuộc tính này và lỗi về thuộc tính này sẽ biến mất.

+0

Bây giờ, khi tôi bấm vào "Đăng ký" nó chỉ cần tải lại trang và các giá trị vẫn còn đầy nhưng không có gì xảy ra ... Cũng không thêm nó vào cơ sở dữ liệu – nielsv

+0

@ niels123, bạn đã thử gỡ lỗi chưa? Ít nhất những gì bạn có thể làm là sử dụng một số khóa có ý nghĩa thay vì chuỗi rỗng cho 'AddModelError' và hiển thị nó ở đâu đó trên trang với Html.ValidationMessage - điều này sẽ hiển thị nếu ngoại lệ xảy ra. Nhưng vẫn còn, cách tốt nhất để hiểu những gì đi sai là chỉ để gỡ lỗi các phương pháp. – Andrei

+0

Tôi đã kiểm tra phương thức và mô hình tuyến tính không hợp lệ. Khóa 11 (DistrictID) có giá trị của quận của tôi nhưng Key 12 (Quận) đưa ra một lỗi: "Trường huyện là bắt buộc". – nielsv

Các vấn đề liên quan