2011-02-22 99 views
1

我想盡量使這個儘可能簡單。asp.net mvc和多個模型和模型綁定器

可以說我有一個項目模型和任務模型

我要創建3個任務項目分配給該項目在一個單一的形式

請告訴我要做到這一點的最好辦法?

方法是簡單地接收一個項目還是我需要在那裏..我只需要保存項目(在倉庫中)也保存相關的任務?... 在視圖中...我需要一個viewModel ..我很困惑。請幫助

public ActionResult Create(Project p){ 

} 

回答

1

這裏的我會怎樣着手:

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

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

然後有一個控制器:

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!" /> 
} 

和相應的任務編輯器模板(~/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

添加的Task模型的集合到Project模型,並使用foreach循環來顯示的任務,或重複,知道如何顯示單個任務的局部視圖。