2013-06-10 2 views
1

MultiSelectList의 dataValueField는 코드 숨김 모델의 숫자이고 dataTextField 필드는 string입니다.숫자 ID 값에 대한 MultiSelectList 유효성 검사

결과 html select 요소에서 여러 값을 선택하면 유효성 검사 오류가 발생하여 must be a number 필드가 표시됩니다. 이것은 뒷받침 필드가 정수이기 때문에 의미가 있으며 여러 항목을 선택하면 건물의 id 값이 쉼표를 사용하여 연결됩니다. 이 문제를 해결할 수있는 방법은 무엇입니까? 감사.

모델은 다음과 같습니다.

// Selected buildings are stored in this table. 
public class ClientSelectedBuildings 
{ 
    public int ClientSelectedBuildingsId { get; set; } 
    // ... 
    [Display(Name = "Please select the buildings under consideration.")] 
    public int? BuildingId { get; set; } 
} 

// Building list is retrieved from this table. 
public class Buildings 
{ 
    public int BuildingsId { get; set; } 
    // ... 
    [StringLength(255)] 
    public string BuildingName { get; set; } 
} 

내보기는 다음과 같습니다.

@model TheApplication.Models.ClientSelectedBuildings 
    <div class="outer"> 
     <div class="inner"> 
      @Html.LabelFor(t => t.BuildingId) 
      @Html.ListBoxFor(t => t.BuildingId, (MultiSelectList)ViewBag.Buildings, new { size = "4" }) 
      @Html.ValidationMessageFor(t => t.BuildingId) 
     </div> 
    </div> 

답변

2

도메인 모델은 하나의 BuildingId 만 허용하지만 양식은 목록 상자를 통해 여러 번 보내려고합니다.

도메인 모델이 뷰 모델과 완벽하게 일치하지 않는 완벽한 예입니다. 도메인과 뷰는 각각 서로 다른 관심사를 가지고 있으며 매우 기본적인 CRUD 상황을 벗어나면 폼보기에는 항상 별도의 모델이 필요하다는 것을 알게 될 것입니다.

사용자 지정 모델 바인더없이 ClientSelectedBuildings에 직접 바인드 할 수 없습니다. 대신 중간 모델에 바인딩 한 다음 여러 ClientSelectedBuilding에 매핑 할 수 있습니다.

// Here's the model submitted from the view. This will have to be mapped to domain 
// entities. 
public class FormModel 
{ 
    // ... Other form fields ... 

    public int[] BuildingIds { get; set; 

    // ... Other form fields ... 
} 


// Example controller action that processes the form input. 
[HttpPost] 
public ActionResult MyPostAction(FormModel input) 
{ 
    if (ModelState.IsValid) 
    { 
     // Loop all submitted building ids, map the data into domain entities. 
     foreach(var buildingId in input.BuildingIds) 
     { 
      // Create the domain entity. 
      var selected = new ClientSelectedBuildings 
      { 
       ClientSelectedBuildingsId = ... Wherever this comes from ... 
       BuildingId = buildingId; 
      }; 

      // Add to the data repository. 
      this.MyDbContext.ClientSelectedBuildings.Add(selected); 
     } 

     // Submit all changes to the data context. 
     this.MyDbContext.ClientSelectedBuildings.SaveChanges(); 

     // ... Return redirect to success view ... 
    } 

    // ... Return error view ... 
} 
+0

위대한 답변 주셔서 감사합니다! – erdinger

관련 문제