2011-02-22 6 views
1

가능한 한 간단하게 만들려고합니다.asp.net mvc 및 여러 모델 및 모델 바인더

내가 프로젝트 모델과 작업 모델을 가지고 말할 수 있습니다

내가 가장 좋은 방법은이 일을 무슨 하나 개의 형태

에서 해당 프로젝트에 할당 된 3 작업과 프로젝트를 만들려면?

이 메서드는 단순히 프로젝트를 받거나 그 밖에 내가 가질 필요가있는 것이 있습니까? (저장소에있는) 프로젝트를 저장하면 관련 작업도 저장됩니까? ... 보기에서 ... 필요합니까 viewModel .. 혼란스러워.

public ActionResult Create(Project p){ 

} 

답변

1

내가 진행 할 방법은 다음과 같습니다

public class ProjectsController: Controller 
{ 
    public ActionResult Index() 
    { 
     var project = new ProjectViewModel 
     { 
      // Fill the collection with 3 tasks 
      Tasks = Enumerable.Range(1, 3).Select(x => new TaskViewModel()) 
     }; 
     return View(project); 
    } 

    [HttpPost] 
    public ActionResult Index(ProjectViewModel project) 
    { 
     if (!ModelState.IsValid) 
     { 
      // The user didn't fill all required fields => 
      // redisplay the form with validation error messages 
      return View(project); 
     } 

     // TODO: do something with the model 
     // You could use AutoMapper here to map 
     // the view model back to a model which you 
     // would then pass to your repository for persisting or whatever 

     // redirect to some success action 
     return RedirectToAction("Success", "Home"); 
    } 
} 

다음 뷰 (~/Views/Projects/Create.cshtml) :

@model AppName.Models.ProjectViewModel 
@using (Html.BeginForm()) 
{ 
    <div> 
     @Html.LabelFor(x => x.ProjectName) 
     @Html.EditorFor(x => x.ProjectName) 
     @Html.ValidationMessageFor(x => x.ProjectName) 
    </div> 

    @Html.EditorFor(x => x.Tasks) 

    <input type="submit" value="Create!" /> 
} 

하고 해당 작업 편집기 템플릿

public class TaskViewModel 
{ 
    public string Name { get; set; } 
} 

public class ProjectViewModel 
{ 
    public string ProjectName { get; set; } 
    public IEnumerable<TaskViewModel> Tasks { get; set; } 
} 

는 다음 컨트롤러가 (~/Views/Projects/EditorTemplates/TaskViewModel.cshtml) :

@model AppName.Models.TaskViewModel 
<div> 
    @Html.LabelFor(x => x.Name) 
    @Html.EditorFor(x => x.Name) 
    @Html.ValidationMessageFor(x => x.Name) 
</div> 
0

Project 모델에 Task 모델의 컬렉션을 추가하는 데 도움과 작업을 표시하거나 하나의 작업을 표시하는 방법을 알고있는 부분보기를 반복하는 foreach 루프를 사용하십시오. 여기