Accessing model data from a controller
In this fragment I am going to explain how to retrieve
data from database by controller and display using view template. If you are
new to the MVC refer part1.
Step 1: Add
controller to your MyMVCMovieList project. Choose and add
following details to your controller when adding,
- Controller Name :- MovieController
- Template: - Controller with read/write actions and views, using Entity Framework.
- Model class: - Movie (MvcMovie.Models).
- Data context class: - MovieDBContext (MvcMovie.Models).
In ASP.NET MVC 4 automatically create the CRUD (view
templates for create, edit, delete, index and details) action methods and views.
Run the application and browse the Movie controller by appending
/Movie to the URL. It show up page same as index,
because we haven’t add anything yet.
Click on create movie button
and create couple of movies. Try delete and edit too.
Movie Create page
Movie List
Let’s go through the generated
code.
Open the MovieController.cs file look at the Index method.
Above code is for to get all
entries of movie table of database and to pass them to the view.
Now look at the generated
Details method.
Above
method says, an instance of Movie model pass in to the view (ASP.NET MVC provides
the ability to pass strongly typed data or objects to a view template. This
strongly typed approach enables better compile-time checking of your code and
richer IntelliSense in the Visual Studio Express editor.).
Let’s move
to view templates. When examine all generated .cshtml files you will notice
there is word a
@model. It
represents the type of object that the view expecting. As the example let’s
take Index view and the Index method in MovieControlller. In method return the
details of all movies stored in database, in view displays data returned from
the controller.
Hi, nice blog you have! Keep it active, good job man!
ReplyDelete---
devmain