Is it considered bad practice to have multiple views for same URL in MVC, based on different user roles? For example: 开发者_开发知识库http://www.domain.com/ViewProductID/123 will show a "normal" product page for a regular user and it will show an "enhanced" (product stats, ability to edit title etc..) version to someone logged in as admin.
If it's bad practice, why? If it's ok, what's the best way to implement it? 2 separate templates or 1 template scattered with if..else?
Thanks!
I think it's fine to modify the view based on context; it happens all the time. Whether you do the if.. else or the multiple aspx files is really dependant on how much is different. A couple alternate options:
1) use Html.RenderAction to call against an AdminController actions to embed the stuff, the AdminController can return empty results if the user isn't an admin
or, better:
2) use a different Master page based on the user's role / status. This way, you can pull the logic for setting the master into an actionfilter ot he like, and do it one time but apply it wherever it makes sense. Just make sure that the alternate Master pages are compatible w/ the views in terms of the contentplaceholderId's.
If the pages aren't going to be drastically different (i.e. they show the same data, possibly with more for admins) then I would say put all of the code in the same file. If possible, use a role-based ability management system so that you can ask things like the following:
if can? :create, Users do
...
else
...
end
Then, you setup your abilities so that admins and managers can both create users. This way, you don't have to worry about who the user is, only what the user is allowed to do.
Basically you're talking about permissions resulting in different pages, which is a very common thing to do. Think about the default landing page on Facebook for 2 different people.
Implementation is the same as for anything else: combine common elements where you can for reuse. Simple differences might just go in if..else and more complex differences belong in different templates.
In my opinion it is fine to have the same url for users and admins. the real question is around usability for your users. Does this have any impact on them? A lot of sites using MVC present addition content or links depending on the level of authorization.
What framework and language are you using? You might not need a completely different template if you have something like partial views available to you.
精彩评论