【发布时间】:2011-04-16 20:59:46
【问题描述】:
我刚开始学习 ASP.NET MVC 3。我一直在浏览 ASP.NET 网站上的音乐商店示例,并开始开发自己的网站,但我遇到了一些麻烦了解我应该如何设置我的控制器操作方法。
在我的网站上,每个登录的用户都可以在他们的项目上执行标准的 CRUD 操作。我在 ProjectController 上使用以下操作方法将其设置为类似于 Music Store 示例。到目前为止,这对我来说是有意义的。
ActionMethod View
ProjectController.Index() Lists the active users's projects
ProjectController.Details(int id) Shows details for project 123
ProjectController.Create() Shows a form to edit a new project
ProjectController.Create(FormCollection col) Adds a new project with the form contents
ProjectController.Edit() Shows a form to edit a new project
ProjectController.Edit(int id, FormCollection col) Adds a new project with the form contents
ProjectController.Deiete(int id) Shows a delete confirmation form
ProjectController.Delete(int id, FormCollection col) Deletes a project with the provided id.
此外,用户将能够向每个项目添加项目。项目不能单独存在,必须在创建时与项目相关联。我难以理解的是如何传递对应该在其中创建项目的项目的引用。例如,在我的项目控制器中,我有一对类似于上述控制器的 Create() 操作方法。
ItemController.Create() Shows a form to create a new item
ItemController.Create(FormCollection col) Creates a new item with the details from the form.
但我不明白第一个 Create() 方法如何将引用传递给应在其中创建新项目的项目,因为 View() 辅助方法只能接受一个对象参数。我应该只将项目的引用添加到 ViewBag 的属性中吗?我也是动态类型的新手,此时 ViewBag 对我来说似乎很神奇。所以我有点犹豫要不要使用它。我也一直认为强类型设计更好。那么我应该创建一个单独的“NewItemData”模型对象,其中包含对新项目的引用以及它要添加到的项目吗?
一旦表单知道它正在向哪个项目添加项目,它应该如何在提交时将这些信息传回?表单中是否应该有一个隐藏的“ProjectID”字段?还是应该将表单 POST 返回到查询字符串中包含项目 ID 的 URL?
www.mysite.com/Item/Create?ProjectID=1234
最后,我还希望能够列出添加到每个项目中的项目。这应该是 ItemController 还是 ProjectController 的一部分。为简单起见,我坚持使用默认的 Controller\Action[ID] URL 路由。下面列出了我的一些想法。我倾向于最后一个选项,但真的很想听听其他有更多经验的人的想法。
Action Method URL
ItemController.Index(int ProjectID) \Item?ProjectID=1234
ItemController.List(int id) \Item\List\1234
ProjectController.Items(int id) \Project\Items\1234
【问题讨论】:
标签: asp.net asp.net-mvc actionmethod