mvc3 的新手,我有几个问题,如果有人可以回答/提供链接,我将不胜感激:
谢谢!
最佳答案
When should I use View Models? Is it not recommended to use the domain? I find that my view models are copies of my domain objects, and don't see the value...
应始终使用 View 模型。您不应在 View 中使用域模型。
View 模型不是领域模型的精确副本。它们总是有一些与 View 的特定要求相关的差异。例如,您希望在一个屏幕上展示您的域模型的一些属性,而在其他屏幕上展示其他属性。因此,您还将有不同的验证要求,因为一个屏幕上需要一个属性,而另一个屏幕上不需要。因此,您还将在这些 View 模型上拥有不同的数据注释。
When should I use Partials? Is it only if the partial view will be reused?
不仅 View 将被重用。部分可用于使您的 View 更有条理。此外,如果您使用 AJAX,则使用部分功能会更容易。您可以将 AJAX 请求发送到 Controller 操作,该操作将返回部分 View ,允许您仅更新 DOM 的一部分。
When should I use Display Templates and Editor Templates? Can I use these without a view model?
总是。您可以将它们与任何强类型模型一起使用,但您应该始终使用 View 模型(请参阅对上一个问题的回答)。
How do I create an edit screen where the parent and list of child objects are both editable? i.e. a few fields at the top (parent) and a grid of fields below (like editable rows), particularly, how do i do the binding? automapper is not used.
这是一个相当广泛的问题,但要像往常一样回答它,首先要定义 View 模型,该模型将表示/包含您希望在此屏幕上显示以进行编辑的属性:
public class ChildViewModel
{
[Required]
public string Name { get; set; }
}
public class ParentViewModel
{
[Required]
public string Name { get; set; }
public IEnumerable<ChildViewModel> Children { get; set; }
}
然后是 Controller :
public class HomeController: Controller
{
public ActionResult Index()
{
// TODO: Fetch an actual domain model from your repository,
// and map it to the view model (AutoMapper is a great tool for the job)
var model = new ParentViewModel
{
Name = "parent name",
Children = Enumerable.Range(1, 5).Select(x => new ChildViewModel
{
Name = "child " + x
})
};
return View(model);
}
[HttpPost]
public ActionResult Index(ParentViewModel model)
{
if (!ModelState.IsValid)
{
return View(model);
}
// TODO: the model object here will contain the new values
// => user AutoMapper to map it back to a domain model
// and pass this domain model to the repository for processing
return RedirectToAction("Index");
}
}
最后是 View :
@model ParentViewModel
@using (Html.BeginForm())
{
<h2>Parent</h2>
<div>
@Html.LabelFor(x => x.Name)
@Html.EditorFor(x => x.Name)
@Html.ValidationMessageFor(x => x.Name)
</div>
<h2>Children</h2>
<table>
<thead>
<tr>
<th>Child name</th>
</tr>
</thead>
<tbody>
@Html.EditorFor(x => x.Children)
</tbody>
</table>
<input type="submit" value="OK" />
}
最后一 block 是一个 child 的编辑器模板(
~/Views/Home/EditorTemplates/ChildViewModel.cshtml
):@model ChildViewModel
<tr>
<td>
@Html.LabelFor(x => x.Name)
@Html.EditorFor(x => x.Name)
@Html.ValidationMessageFor(x => x.Name)
</td>
</tr>
关于asp.net-mvc-3 - 我什么时候使用 View Models、Partials、Templates 并使用 MVC 3 处理子绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6157348/