Wade73
Wade73

Reputation: 4509

MVC Views from Database

I am building an ASP.Net MVC 2 application for a client and it requires the ability for user to define views. On this website it shows how to do this - http://www.umbraworks.net/bl0g/rebuildall/2009/11/17/ASP_NET_MVC_and_virtual_views , but I ran into a few comments there and elsewhere that this was a bad idea. What would be the best way to accomplish allowing users to define the whole page? Also, why is the database a bad idea? Thanks.

Wade

Upvotes: 9

Views: 1567

Answers (2)

Jim
Jim

Reputation: 424

Well if you can write the application using MVC 3 Beta instead of MVC 2 you can use this technique:

http://buildstarted.com/2010/11/02/razor-without-mvc-part-ii/

You can store your "View" as string in the database then just pull it out and pass it to the parse engine and you are all set.

It works great.

Upvotes: 6

Christopher Edwards
Christopher Edwards

Reputation: 6659

OK, I'm no great authority on this but...

I guess the reason it could be a bad idea is you are giving the user root level access to the app, after all arbitrary code can be run from a view. Also the views will not be checked or tested by programmer, they might not compile or they might have other issues.

You can parse the text supplied by the user that forms the view and try and sanitise it but this is going to be hard. Although having the MVC view engine as your CMS looks like you are getting the framework to do the heavy lifting for you it's too powerful; expressing in code what the user can't do is harder than expressing in code what they can do. That's why (maybe) this site uses markdown rather than HTML for markup in the questions and answers.

As for the database being a bad idea I think people might be anti this because of a perceived problem with hitting the db hard. However I'm not sure this is an insurmountable issue; the view will probably be cached after it has been jit'ed, although I'm not certain, you'll need to test this. If so you'll have to find a way of causing the jit to run again when a view is edited, or you'll have to recycle the site. I assume forcing a re-jit exists because when you change an aspx file in a non-precompiled site the framework gets a file change notification from the OS and the updated view is then jit'ed again next time it's accessed. Even if I'm wrong and the view is pulled out of the db and jit'ed every time it's used you should be able to use caching to stop this happening too much.

In some situations views in a db might be the best approach, for example if the users creating the views are programmers. I'd consider it very carefully.

As for alternative a CMS toolkit (N2, Orchard etc.) might be a good idea.

Upvotes: 1

Related Questions