[英]ASP.NET MVC: Do I really have to create one view per action?
If I have a fairly crud-based area of my app, do I really have to create separate "Create" and "Edit" views? 如果我的应用程序具有相当粗糙的区域,是否真的需要创建单独的“创建”和“编辑”视图? The HTML will be practically the same. HTML几乎是相同的。 I want an "Edit" and "Create" action to both render a "Show.aspx" view, but certainly Resharper 5 is complaining about there being no "Show" action. 我希望“编辑”和“创建”动作都呈现“ Show.aspx”视图,但是肯定Resharper 5抱怨没有“显示”动作。
What's the best practice? 什么是最佳做法?
There are alternatives. 还有其他选择。 Basically off the top of my head you have three options. 基本上,我有三种选择。
You don't "have" to do anything. 您没有“要做”任何事情。 MVC is based on conventions, which are valuable, but these are not technically required. MVC基于约定,这些约定很有价值,但是在技术上并不是必需的。 In your case, I think it's more important to avoid redundant code. 对于您的情况,我认为避免冗余代码更为重要。
You might consider having only an "Update" action and an Update.aspx view (form) to go with it. 您可能会考虑只使用一个“ Update”操作和一个Update.aspx视图(窗体)。
Use the same form for both creating and updating. 使用相同的表单进行创建和更新。 The only difference is, when creating, the form won't have an object ID. 唯一的区别是,在创建时,表单将没有对象ID。
After submitting, if the Update action sees an ID, it loads the object. 提交后,如果“更新”操作看到一个ID,它将加载该对象。 If not, it instantiates a new one. 如果没有,它将实例化一个新的。 Then just update the properties from the form, and commit (save). 然后只需从表单更新属性,然后提交(保存)。
So, one action and one view. 因此,一举一动。 Less code and it keeps convention. 更少的代码,并且保持惯例。
You can specify which view you want the controller method to use, so there is no strict requirement for having two different views. 您可以指定要使用控制器方法的视图,因此对两个不同的视图没有严格要求。
If your Add and Edit views look exactly the same, but you want to make it clear to the user whether they are adding or editing, you can simply push a different title into the ViewData, and display it in the shared view. 如果您的“添加”和“编辑”视图看起来完全相同,但是您想让用户清楚他们是要添加还是编辑,则只需将另一个标题推入ViewData,然后在共享视图中显示即可。
You can also put views in the "shared" folder, or create .ASCX partials that can be shared. 您也可以将视图放在“共享”文件夹中,或创建可以共享的.ASCX部分。
Go for it. 去吧。 It makes perfect sense. 这是很合理的。 View should always be set up for front-end developers convenience, as controllers can pass data to any view, without any extra effort. 应该始终为前端开发人员提供方便而设置视图,因为控制器可以毫不费力地将数据传递到任何视图。 You shouldn't feel restricted to do something, just because ReSharper says so. 您不应该仅仅因为ReSharper这样说而感到被限制。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.