I develop websites using web-forms, now I have a project where I am using MVC3 Framework with Rzor. My question is about some basic design patterns in MVC. I have a Webpage, where on left side i will Pull Categories from SQL Table, In Center I will Query another Sql Table, and few more all over the page.
So my question is…whats the best way to bring data into one webpage, all these queries are totally independant, do I need to create new MODEL for every Query? or there is a better way of doing it?
in WebForms I used user controls, where every user control had its own design & Sql Queries. I have heard about using Partial Views in MVC, but i am not sure, I guess i am having hard time understanding how to bring data into one webpage using different queries & show output on webpage.
Thanks
You should create a
ViewModel. Look at Update belowThis is a model that represents your page. The elements you want to show in your view should exist in your ViewModel. You will populate the ViewModel in your controller and display them on the page.
I’ve written an example of a shopping site page, with categories on the left and Products in the centre. Both entities would exist in different tables.
Example:
In your controller:
Then in your view you display it appropriately:
Update
This is about your comment where you mentioned that your database tables and columns change regularly.
I can’t say for sure but maybe you shouldn’t be making tables like that everyday, maybe there is a better database design you could have, or maybe an RDBMS isn’t the right thing for you and you should look into a NoSql database (like MongoDB )
Nevertheless if you continue with the above code I suggest putting this into a data layer class of its own.
Also take a look at Dapper it’s a very thin data access layer that just gets objects from the database with sql queries or stored procedures. (Just exactly what you need) It’s made and used by stackoverflow.