【发布时间】:2010-09-12 05:17:05
【问题描述】:
是否有人为 MVC 中的操作建立了良好的命名约定?我专门研究了 ASP.net MVC,但这是一个普遍的问题。例如,我有一个显示登录屏幕 (Login) 的操作和一个处理来自该页面的登录请求 (LoginTest) 的操作。我对名字不感兴趣,我还有很多申请要写。
【问题讨论】:
标签: asp.net-mvc model-view-controller
是否有人为 MVC 中的操作建立了良好的命名约定?我专门研究了 ASP.net MVC,但这是一个普遍的问题。例如,我有一个显示登录屏幕 (Login) 的操作和一个处理来自该页面的登录请求 (LoginTest) 的操作。我对名字不感兴趣,我还有很多申请要写。
【问题讨论】:
标签: asp.net-mvc model-view-controller
MS 的 Rob Conery 建议了一些有用的 RESTful 风格的动作命名。
* Index - the main "landing" page. This is also the default endpoint. * List - a list of whatever "thing" you're showing them - like a list of Products. * Show - a particular item of whatever "thing" you're showing them (like a Product) * Edit - an edit page for the "thing" * New - a create page for the "thing" * Create - creates a new "thing" (and saves it if you're using a DB) * Update - updates the "thing" * Delete - deletes the "thing"
导致 URL 类似于(对于论坛)
* http://mysite/forum/group/list - shows all the groups in my forum * http://mysite/forum/forums/show/1 - shows all the topics in forum id=1 * http://mysite/forums/topic/show/20 - shows all the posts for topic id=20
【讨论】:
Rails 对 CRUD 操作有一个很好的操作命名约定:Rails Routing from the Outside In。
HTTP Verb Path Controller#Action Used for
GET /photos photos#index display a list of all photos
GET /photos/new photos#new return an HTML form for creating a new photo
POST /photos photos#create create a new photo
GET /photos/:id photos#show display a specific photo
GET /photos/:id/edit photos#edit return an HTML form for editing a photo
PATCH/PUT /photos/:id photos#update update a specific photo
DELETE /photos/:id photos#destroy delete a specific photo
这本质上是对Paul Shannon's answer 的更新, 因为他的消息来源(Rob Conery)含蓄地说他从 Rails 复制了他的列表。
【讨论】:
我找到了一个blog post by Stephen Walther,对于找到一致的命名方案很有用。他也源自 REST 风格的命名方案,他解释了一些独特的例外情况。
【讨论】:
Stephen Walther 在ASP.NET MVC Tip #11 – Use Standard Controller Action Names 上的帖子可能会澄清您关于MVC Action 命名约定的命名约定...
【讨论】:
内置的 Django 动作后缀为 _done。所以 LoginDone 将是处理登录的页面(在 ASP.NET MVC 驼峰样式中)。
【讨论】:
您使用哪种约定来命名控制器动作是相当不相关的,只要它对您来说是一致的并且易于被使用它的人理解即可。
就您的登录操作而言,LoginDone 很好,同样,ProcessLogin 也很容易理解,因此请使用您觉得舒服的约定。
就我个人而言,我可能会支持 Login 和 ProcessLogin,因为 LoginDone 可能会稍微误导 Action 正在做什么——这当然是假设 Action 正在对用户的凭据做出反应并检查它们是否有效。然后,您可以在登录成功后传递到另一个名为 LoginDone 的操作,如果不是,则传递到 LoginFailed。
【讨论】: