ASP. NET mvc4 entry (5) access model data in Controller

Source: Internet
Author: User

Link: http://www.asp.net/mvc/tutorials/mvc-4/getting-started-with-aspnet-mvc4/accessing-your-models-data-from-a-controller

In this section, we will create a new moviescontroller class and writeCodeTo retrieve the data related to movie, and then use the view template for presentation.

Before proceeding to the next stepProgramGenerate the following.

Right-click the controllers folder to create a new moviecontroller. If you do not enter the following options (right-click the project, build), the following options will not appear:

    • Controller name: moviescontroller.
    • Template: MVC controller with read/write actions and views, using Entity Framework.
    • Model class: Movie (mvcmovie. models ).
    • Data context class: moviedbcontext (mvcmovie. models ).
    • Views: razor (cshtml ).

Click "add". Visual Studio creates the following files and folders:

    • Create a moviescontroller. CS file in the controllers folder of the project.
    • Create a movies folder under the views folder of the project.
    • Create. cshtml, delete. cshtml, details. cshtml, Edit. cshtml, and index. cshtml in the new views \ movies folder.

ASP. net mvc 4 will automatically create the crud (create, read, update, and delete) Action methods and views (the behavior of automatically creating crud actions and views is called scaffolding ). Now we have a complete functional web application that allows us to create, edit, browse, and delete movie data.

Run the program to access moviescontroller by adding/movies behind the URL in the address bar. Because our application depends on the default routing rules (defined in global. in the asax file), when http: // localhost: xxxx/movies is requested, it is automatically routed to the index Action Method of moviescontroller. In other words, the request http: // localhost: xxxx/movies is the same as the request http: // localhost: xxxx/movies/index. The returned result is an empty list because we do not have any data.

Create a movie

Select the create new hyperlink. Enter the details of a movie and click the create button.

Click the create button to submit the form to the server. The server saves the movie data to the database. Then browse/movies again. This time, we can see the newly added data.

Create more data and try the edit, details, and delete hyperlinks. These are all available.

To see the generated code

Open the controllers \ moviescontroller. CS file to view the generated index method. The following shows some code in moviescontroller.

 
Public class moviescontroller: controller {private moviedbcontext DB = new moviedbcontext (); // get:/movies/Public actionresult index () {return view (dB. movies. tolist ());}

The following code instantiates a previously mentioned moviedbcontext object, which is the context of the Movie Database. You can use it to query, edit, and delete data.

 
Private moviedbcontext DB = new moviedbcontext ();

The moviescontroller request will return all data in the movies table in the database and pass the data to the view of the index.

Strong model and @ model keywords

PreviousArticleWe know how a controller transmits data to the view template through the viewbag object. The viewbag object is a dynamic object that provides a convenient and advanced binding method to transmit data to the view.

ASP. net mvc also provides the ability to pass strong data types to view templates. This type of strong data provides better code check during compilation and smart prompts for Visual Studio. The scaffolding mechanism uses this method to create methods and views in moviescontroller and view templates.

View the generated details method in the controllers \ moviescontroller. CS file. The code for the details method in moviescontroller is as follows.

 
////Get:/movies/details/5 PublicActionresult details (IntId =0) {Movie=DB. Movies. Find (ID );If(MOVIE =Null){ReturnHttpnotfound ();}ReturnView (movie );}

If the data of the specified ID can be found, the instance of a movie object will be passed to the view of deatils. Let's take a look at the views \ movies \ details. cshtml file.

By introducing the @ model statement at the top of the view template, we can specify the expected object type of the view. When we create moviescontroller, Visual Studio automatically includes the following statement at the top of the details. cshtml File

 
@ Model mvcmovie. Models. Movie

@ Model command allows us to access the movie data transmitted to view by the Controller through a strongly typed model object. For example, in the details. cshtml template, a model object of the strong type is passed in the code to pass the data of the desired movie object to the displaynamefor and displayfor methods. The create and edit methods and view templates are all passed movie type model objects.

Let's take a closer look at index. cshtml and moviescontroller. the content of the index method defined in CS. note how to create a list object when calling the view method in the code of the index method. The Code passes the created list object from the Controller to the view.

 
PublicActionresult index (){ReturnView (db. Movies. tolist ());}

When you create a moviescontroller, Visual Studio automatically adds the @ model statement at the top of the index. cshtml page.

 
@ Model ienumerable <mvcmovie. Models. Movie>

This @ model command allows us to access the data passed to the view by the Controller through a strongly typed model object. For example, in the index. cshtml template, the Code uses a foreach statement to traverse the model object.

@ Foreach ( VaR Item In  Model ){ <Tr> <TD> @ Html. displayfor (modelitem => Item. Title) </TD> <TD> @ Html. displayfor (modelitem => Item. releasedate) </TD> <TD> @ Html. displayfor (modelitem =>Item. Genre) </TD> <TD> @ Html. displayfor (modelitem => Item. Price) </TD> <TD> @ Html. actionlink (  "  Edit  " , "  Edit  " , New {Id = item. ID}) | @ Html. actionlink (  " Details  " , "  Details  " , New {Id = item. ID}) | @ Html. actionlink (  "  Delete  " , "  Delete  " , New {Id = Item. ID }) </TD> </tr> } 

Because Model objects are strongly typed (ienumerable <movie> objects), the items in the foreach loop are of the movie type. This means that we can get support for security checks during compilation and smart prompts for.

Working with databases

Note: The original article uses the SQL Server localdb database that comes with Visual Studio 2012. This article uses the SQL Server express that comes with visual stuio 2010.

The code first mode of Entity Framework will detect that the database connection string points to a non-existing movies database, so code first will automatically create this database. You can verify this by viewing the app_data folder. If you cannot see the movies. MDF file, click "show all fiels" in the toolbar above Solution Explorer, click "refresh", and expand the app_data folder.

Double-click movies. MDF to open the database browser. Expand the tables folder to view the movie table.

Right-click the movies table and select "show table data" to view the created data.

Right-click the movies table and choose "Open table definition" to view the table structure created for us by Entity Framework code first.

Note how the movies table structure corresponds to the previously created movie class. Entity Framework code first automatically creates a table structure based on the movie class.

When you complete these operations, right-click the database and select "close connection". If you do not do this, an error may be reported when you open the project next time.

Now we have a simple page to show the data in the database. In the next article, we will view the remaining automatically generated code, and add a searchindex method and a searchindex view to find the data in the database.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.