How to create simple Asp.Net MVC website, retrieving data from database and print it in View
Simple - asp.net mvc tutorial.
Project we will learn how to create basic WebSite in Asp.Mvc from 0, retrieve
and show data from database in our views.
+ Connect asp.net mvc to sql server
There are many images but is quite short
used: Visual Studio 2012, Sql Server 2008
2) Asp.Net MVC 3 Project
3) Select just empty project
4) So the base from our WebSite looks like this
5) Add basic elements, first add the master page
7) In my case i separate the
site in 2 main blocks, first the menú and the second is the content that will
change between each page (view)
8)Go to the Content folder enter to Site.css and
delete all the code that this file have, then add the 3 main clases that we use
in our master page and finally include this stylesheet in the header
9) Adding our main Views and folders: in this case
we will have only 2 sections, the Home and the Catalog that will show the data
10) Repeat the same for Home and Catalog
11) Repeat this step for cátalog folder to, is the
12) So now we
have 2 views and 1 master page
13)But if we compile the project and try to run it
we will get this error
14) So the next step is to add the controllers for
15)Name of the folder is the same as name of
16)Compiling again and it Works!
17)Now back to
master and add 2 item menu that will switch between Home and Catalog, and add “ítem
menú css” class to site.css.
step delete the codebehind from the masterpage and change Inehrits to Inherits="System.Web.Mvc.ViewMasterPage"
allow us to use HTML class in the next step
18) Add links
to our views and add some style to menu items
TEXT, ACTION IN CONTROLLER, CONTROLLER)
19) Current result, now we can switch between our
two views and see the result.
20) Add basic
text to the main View “HOME” like this:
Now we will
do something more complicated but interesting to know, retrieving data from the
database and show it in one of our Views in this case just simpe Catalog of
section you must see this basic tutorial how to connect and retrieve data from
database in Asp.Net, its similar in this tutorial.
assume that you can understand the basic connection procedure.
add model class, in this one we will connect to database and retrieve data to
Controller, and then Controller will pass the data to View, in this case just
sample Catalog in Sql Server like this:
add this sample code to the model, this method will retrieve this 3 articles
use the model created in the Catalog Controller, this one will pass the data to
the view through the ViewData.
finally print the data in your View, in this case Products catalog.
26) Final Result:
I hope this tutorial can help somebody!