안녕하세요. 현재 내가하고있는 일에 대해 올바른 접근법을 찾기 위해 고심하고 있습니다. 그래서 물어볼 것이라고 생각했습니다.MVC3에서 SelectList로 ViewModel 매핑하기
엔티티는 EF CodeFirst와 뷰 모델로 사용에 기반 유형을 중첩이 AutoMapper 매핑되고 :
여기 내 간단한 코드입니다.
양식을 게시 할 때 dropdownlist가 model.CourseId에 매핑되고 CourseId = 2, CourseList = Null 인 동시에 [필수] 특성을 갖는 경우에만 유효하지 않기 때문에 ModelState가 유효하지 않습니다. CourseId가 필요하지만 관련 오류 메시지가 필요합니다.
나는 Create GET & POST 액션에서 뷰에 CourseId가 있어야한다고 생각했지만 아직 드롭 다운으로 표시하고 채우는 것이 필요하고 올바르게 수행하는 방법은 확실하지 않았습니다.
나는 이것이 올바르게 사용되어야하는 방법을 이해하지 못할 수도 있습니다. 물론 CourseName이 필요한 경우에도 (즉, 데이터베이스에 이미 존재하는 코스이기 때문에 선택한 키를 보여줄 수있는 외래 키가 필요합니다. .
컨트롤러 작업의 모든 매핑과 데이터 설정을 별도의 서비스 레이어로 분해 할 계획이지만 현재는 작은 프로토 타입입니다.
// Entities
public class Recipe {
public int Id { get; set; }
public string Name { get; set; }
public Course Course { get; set; }
}
public class Course {
public int Id { get; set; }
public string Name { get; set; }
}
// View Model
public class RecipeCreateViewModel {
// Recipe properties
public int Id { get; set; }
public string Name { get; set; }
// Course properties, as primitives via AutoMapper
public int CourseId { get; set; }
public string CourseName { get; set; }
// For a drop down list of courses
[Required(ErrorMessage = "Please select a Course.")]
public SelectList CourseList { get; set; }
}
// Part of my View
@model EatRateShare.WebUI.ViewModels.RecipeCreateViewModel
...
<div class="editor-label">
Course
</div>
<div class="editor-field">
@* The first param for DropDownListFor will make sure the relevant property is selected *@
@Html.DropDownListFor(model => model.CourseId, Model.CourseList, "Choose...")
@Html.ValidationMessageFor(model => model.CourseId)
</div>
...
// Controller actions
public ActionResult Create() {
// map the Recipe to its View Model
var recipeCreateViewModel = Mapper.Map<Recipe, RecipeCreateViewModel>(new Recipe());
recipeCreateViewModel.CourseList = new SelectList(courseRepository.All, "Id", "Name");
return View(recipeCreateViewModel);
}
[HttpPost]
public ActionResult Create(RecipeCreateViewModel recipe) {
if (ModelState.IsValid) {
var recipeEntity = Mapper.Map<RecipeCreateViewModel, Recipe>(recipe);
recipeRepository.InsertOrUpdate(recipeEntity);
recipeRepository.Save();
return RedirectToAction("Index");
} else {
recipe.CourseList = new SelectList(courseRepository.All, "Id", "Name");
return View(recipe);
}
}
CourseId가 Required 속성 인 경우 목록에없는 [필수]'속성을 넣어 ...하지만 nullable이 아니기 때문에 필요하지 않을 수도 있습니다. 목록에서 제거하십시오. –
사물을 단순화시킴으로써 약간 혼란스럽게 만들었습니다. CourseId는 엔티티 모델에 [Required] 속성을 가지고 있습니다.이 속성은 EFCodeFirst를 통해 SQL Compact 데이터베이스에서 필수 입력란으로 사용됩니다. 이전에 엔티티를 직접 사용했기 때문에이를 내 뷰 모델로 전송한다고 생각한 실수를했을 수도 있습니다. CourseList 속성에서 필수 속성을 제거했습니다. 이는 실수였습니다. – Pricey
아직 답변이 없으므로이 소스를 업데이트하고 정확한 오류 메시지를 게시합니다. –