开发者

ASP.NET MVC: Do I really have to create one view per action?

开发者 https://www.devze.com 2023-01-02 02:47 出处:网络
If I have a fairly crud-based area of my app, do I really have to create separ开发者_运维百科ate \"Create\" and \"Edit\" views?The HTML will be practically the same.I want an \"Edit\" and \"Create\" a

If I have a fairly crud-based area of my app, do I really have to create separ开发者_运维百科ate "Create" and "Edit" views? The HTML will be practically the same. 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.

What's the best practice?


There are alternatives. Basically off the top of my head you have three options.

  1. You could either make a user control and have very lightweight edit and create pages.
  2. If you are using ASP.MVC 2 you can capture the layouts as attributes on your view model and use the new template helpers DisplayFor and in your edit / create case EditorFor / EditorForModel.
  3. You can specify a view name on the call to View from your controller action.


You don't "have" to do anything. MVC is based on conventions, which are valuable, but these are not technically required. 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.

Use the same form for both creating and updating. The only difference is, when creating, the form won't have an object ID.

After submitting, if the Update action sees an ID, it loads the object. 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.

You can also put views in the "shared" folder, or create .ASCX partials that can be shared.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消