我对视图模型还比较陌生,使用时遇到了一些问题。这里有一个情况,我想知道最佳实践是什么...
我将视图所需的所有信息都放入视图模型中。以下是一个示例,请原谅任何错误,这是我临时编写的代码。
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);
}
如果屏幕只允许编辑一个或两个字段,那么当视图模型返回时,会缺少很多数据(这是应该的)。
(Note: I have retained the HTML tags as requested and made the text more clear and concise.)
[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 incomplete.
model.MapTo(project); // Extension method using AutoMapper.
ProjectService.UpdateProject(project);
// Add a message for the user to temp data.
return RedirectToAction("details", new { project.Id });
}
catch (Exception exception)
{
// Add a message for the user to temp data.
return View(model) // Won't work, view model is incomplete.
}
}
我的临时解决方案是从头开始重新创建视图模型,从域模型中重新填充它,再将表单数据重新应用到它上面,然后像往常一样继续进行。但这使得视图模型参数有点无意义。
[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.
// Recreate the view model from scratch.
model = new ProjectEdit();
model.MapFrom(project); // Extension method using AutoMapper.
try
{
TryUpdateModel(model); // Reapply the form data.
if (!ModelState.IsValid)
return View(model) // View model is complete this time.
model.MapTo(project); // Extension method using AutoMapper.
ProjectService.UpdateProject(project);
// Add a message for the user to temp data.
return RedirectToAction("details", new { project.Id });
}
catch (Exception exception)
{
// Add a message for the user to temp data.
return View(model) // View model is complete this time.
}
}
有没有更优雅的方法?
编辑
两个答案都是正确的,如果可以的话我会把奖励给他们两个。然而,经过尝试,我发现 MJ 的解决方案最为简洁。
我仍然能够使用帮助程序,Jimmy。如果我将需要显示的内容添加到视图包(或视图数据)中,就像这样...
ViewBag.Project= project;
我可以执行以下操作...
@Html.LabelFor(model => ((Project)ViewData["Project"]).Name)
@Html.DisplayFor(model => ((Project)ViewData["Project"]).Name)
这是一个有些取巧的方法,有时需要在域模型上使用 System.ComponentModel.DisplayNameAttribute
进行装饰,但我已经这样做了。
我很想调用...
@Html.LabelFor(model => ViewBag.Project.Name)
但动态表达式会带来一个问题。