2011-02-22 95 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循环来显示的任务,或重复,知道如何显示单个任务的局部视图。