2010-10-19 51 views
0

我正在努力为自己的行为选择适当的名字。我想返回一个以行动来区分:什么是典型的ASP.NET MVC - 控制器动作名称约定?

  1. 创建
  2. 编辑
  3. 编辑,创建

这是我到目前为止有:

 
Create --> Show the Empty Form for Create 
Add --> Receives data from Create and Save New Entity 
Edit --> Shows Existing Entity in a form for editing 
Update --> Saves the changes on an existing Entity 
??? --> Shows the form for either editing or creating depending on the 
      situation 
Save --> Either saves or updates the entity depending on whether the entity 
      already exists or not. 

那么,什么是适当的行动名称显示Create/Edit视图,它将数据发送到Save

我曾考虑过CreateEdit,因为它很清楚明确,但我不确定。有什么建议么?

+1

创建通常是窗体淋浴(GET)和数据接收器(POST)。 – bzlm 2010-10-19 13:16:36

+0

我已经将这些结合在重载中,并想知道这种方法是否有任何优点或缺点。 – bzarah 2010-10-19 13:21:29

+1

@bzarah缺点?不知道任何。优点?使您遵守REST标准。 – bzlm 2010-10-19 13:42:30

回答

4

我通常使用Create()来添加一个新的实体,并使用Edit()来编辑一个。

我超载GET & POST方法和添加[HttpPost]属性的一个接收数据,例如:

public ActionResult Create() 
{ 
    // this one renders the input form 
    ... 
    return View(); 
} 

[HttpPost] 
public ActionResult Create(MyViewModel model) 
{ 
    // this one accepts the form post 
    if (ModelState.IsValid) 
    { 
     ... 
     return RedirectToAction(...); 
    } 
    return View(model); 
} 

这种约定可以很容易找到相关的方法。

+0

所以,创建(新实体),编辑(改变现有),创建/编辑 - > ??? 此外,whate是否将这些行为合并为一个超负荷的优点和缺点? – bzarah 2010-10-19 13:20:47

+0

如果您可以将空模型传递给GET方法并且可以在POST方法中检测到实体是新的,则创建/编辑可以正常工作,例如,通过检查零ID。然而,我的控制器方法非常小,功能也不同 - 也就是说,create方法只是将视图模型对象映射到一个新的实体并保存,而编辑方法加载实体并仅将模型映射到实体 - 不需要以保存更新,如果您使用的是更改跟踪ORM(如NHibernate)。 – 2010-10-19 13:33:35

+0

我们也在这里使用NHibernate,所以保存一个新的实体并更新一个现有的实体可以用同样的方法无缝完成。我很想谈谈重载“显示”和“持续”操作方法的优缺点。我觉得每个单独的动作名称都会导致更清晰的API。这就是说,ASP.NET MVC已经通过ActionMethodSelectorAttributes构建了可扩展性,并且@bzlm指出这更加RESTFful。 – bzarah 2010-10-19 14:35:17