【问题标题】:asp.net mvc and multiple models and modelbindersasp.net mvc 和多个模型和模型绑定器
【发布时间】:2011-02-22 23:17:06
【问题描述】:
我想让这个尽可能简单。
假设我有一个项目模型和一个任务模型
我想创建一个项目,在一个表单中分配给该项目的 3 个任务
最好的方法是什么??
该方法是否会简单地接收一个项目或我还需要在那里拥有什么.. 保存项目(在存储库中)是否也会保存相关任务?...
在视图中...我需要一个viewModel ..我很困惑。请帮忙
public ActionResult Create(Project p){
}
【问题讨论】:
标签:
asp.net-mvc
nested
nested-forms
【解决方案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>
【解决方案2】:
将Task 模型的集合添加到Project 模型,并使用foreach 循环来显示任务,或重复知道如何显示单个任务的局部视图。