我对查看模型比较新,我遇到了一些使用它们的问题.这是一种情况,我想知道最佳做法是什么......
我将视图所需的所有信息都放入视图模型中.这是一个例子 - 请原谅任何错误,这是我的头顶编码.
public ActionResult Edit(int id)
{
var project = ProjectService.GetProject(id);
if (project == null)
// Something about not found, possibly a redirect to 404.
var model = new ProjectEdit();
model.MapFrom(project); // Extension method using AutoMapper.
return View(model);
}
Run Code Online (Sandbox Code Playgroud)
如果屏幕只允许编辑一个或两个字段,当视图模型返回时,它会丢失相当多的数据(应该是这样).
[HttpPost]
public ActionResult Edit(int id, ProjectEdit model)
{
var project = ProjectService.GetProject(id);
if (project == null)
// Something about not found, possibly a redirect to 404.
try
{
if (!ModelState.IsValid)
return View(model) // Won't work, view model is …Run Code Online (Sandbox Code Playgroud)