asp.net MVC4 Introductory tutorial (v): Accessing data model from Controller _ self-study process

Source: Internet
Author: User
Tags table definition actionlink visual studio 2010

In this section, you will create a new Moviescontroller class and write code in this controller class to get the movie data and use the view template to display the data in the browser.

Build the application before you start the next step (make sure the application compiles without problems)

Right-click the Controller folder and create a new Moviescontroller controller. When the build succeeds, the following options appear. Set the following options:

· Controller name: moviescontroller. (This is the default value).

· Templates: MVC Controller with Read/write the actions and views, using the Entity Framework.

· Model class:Movie (mvcmovie.models).

· Data context class: Moviedbcontext (mvcmovie.models).

· Opinion:Razor (CSHTML). (default value).

Click Add. Visual Studio Express creates the following files and folders:

· The MoviesController.cs file in the Project Controller folder.

· The movie folder under the Project View folder.

· Create create.cshtml, delete.cshtml, details.cshtml, edit.cshtml, and index.cshtml files in the new Views\movies folder.

asp.net MVC 4 automatically creates CRUD (create, read, update, and Delete) action methods, and related view files (Crud automatically created action methods and view files are called infrastructure files). Now you have all the Web features you can create, list, edit, and delete movie entity.

Run the application to browse the movies controller by appending the/movies to the URL of the browser's address bar. Because the application relies on the default route (defined in the Global.asax file), the browser request Http://localhost:xxxxx/Movies will be routed to the Movies controller default index Method of operation. In other words, the browser request http://localhost:xxxxx/Movies equivalent to the browser request Http://localhost:xxxxx/Movies/Index. Because you haven't added anything yet, the result is an empty list of movies.

Create a movie

Click the Create new link. Enter some more details about the movie, and then click the Create button.

Clicking the Create button causes the form to be submitted to the server, and the movie information is also saved to the database, and then you are redirected to Url/movies, where you can see the new movie you just created.

Create some more movie data. You can also try clicking on the link to edit, details, and delete features.

Look at the generated code

Open the controllers\moviescontroller.cs file and locate the generated index method. A section of the movie controller and the index method are shown below.

public class Moviescontroller:controller
{
  private Moviedbcontext db = new Moviedbcontext ();
  //Get:/movies/public

  actionresult Index ()
  {return
    View (db). Movies.tolist ());
  }

The following is an instance of the instantiated movie Database context in the Moviescontroller class, as described earlier. The Movie Database context instance can be used to query, edit, and delete movies.

Private Moviedbcontext db = new Moviedbcontext ();

Request to the movies controller to return all records in the Movies Movie Database table, and then pass the results to the index view.

Strongly typed models and @model keywords

In the previous tutorials in this series, you saw using the ViewBag object to pass data or objects from the controller to the view template. ViewBag is a dynamic object that provides a convenient late-bound method for passing information to a view.

ASP.net MVC also provides the ability to pass strongly typed data or object to view templates. This strong type makes it much better to check your code at compile time and provide richer IntelliSense in the Visual Studio Editor. When you create action methods and views, the infrastructure mechanism in Visual Studio uses the Moviescontroller class and view templates.

Look at the generated details method in the controllers\moviescontroller.cs file. The details method in the movie controller is shown below.

Public ActionResult Details (int id = 0)
{
   Movie Movie = db. Movies.find (ID);
   if (movie = = null)
   {return
     httpnotfound ();
   }
   return View (movie);
}

If an instance of a Movie,movie model is found, it is passed to the detail view. Take a look at the contents of the views\movies\details.cshtml file.

By introducing the @model statement at the top of the view template file, you can specify the type of object that the view expects. When you create a movie controller, Visual Studio automatically includes the @model declaration to the top of the details.cshtml file:

@model MvcMovie.Models.Movie

This @model declaration allows the controller to pass a strongly typed model object to the view view so that you can access the strongly typed movie model passed over in the view. For example, in the details.cshtml template, displaynamefor and displayfor HTML Helper pass each field of the movie through a strongly typed model object. Creating and editing methods and view templates are passing the strongly typed model object of the movie.

Take a look at the Index method in index.cshtml view templates and MoviesController.cs . Notice how the code creates the list object in the index action method, and calls the view method.

This code passes the movies list to the view in the controller:

Public ActionResult Index ()
{return
   View (db). Movies.tolist ());
}

When you create a movie controller, Visual Studio Express automatically contains @model statements to the top of the index.cshtml file:

@model ienumerable<mvcmovie.models.movie>

This @model declaration allows the controller to pass a strongly typed movie list model object to the view view. For example, in the index.cshtml template, use a foreach statement to iterate through the list of movies on a strongly typed 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>
     <th>
       @Html. Displayfor (ModelItem => item. Rating)
     </th>
     <td>
       @Html. ActionLink ("edit", "edit", new {id=item.id}) |
       @Html. ActionLink ("Details", "Details", {id=item.id}) |
       @Html. ActionLink ("delete", "delete", {id=item.id}) 
     </td>
   </tr>
}

Because the model object is strongly typed (is a Ienumerable<movie> object), the type of each item object in the loop is the Movie type. One of the benefits is that this means that you can check when code compiles, while supporting more comprehensive IntelliSense in the Code Editor:

Using SQL Server LocalDB

The Entity Framework Code first code takes precedence and automatically creates a database if no database connection string is detected pointing to the movies database. Look in the App_Data folder and you can verify that it has been created. If you don't see the movies.mdf file, on the Solution Explorer toolbar, click the Show All Files button, click the Refresh button, and then expand the App_Data folder.

Double-click movies.mdf to open the Database Explorer, and then expand the Table folder to view the movie table.

Note: If the Database Explorer is not displayed, you can choose to connect to the database from the Tools menu, and then close the Select Data Source dialog box. This will force the Database Explorer to open.

Note: If you are using VWD or Visual Studio 2010, you may see an error message similar to the following:

· Because the database ' C:\Webs\MVC4\MVCMOVIE\MVCMOVIE\APP_DATA\MOVIES. MDF ' is version 706, so it cannot be opened. This server supports databases in versions 655 and earlier. Unable to demote support.

· The SqlConnection provided by "InvalidOperation Exception is unhandled by user code" does not specify an initial database.

You need to install SQL Server data Tools and LocalDB. and verify the Moviedbcontext connection string that you specified earlier.

Right-click the Movies table and select Display table data to view the data that you created.

Right-click the Movies table and select Open Table definition to view the table structure of the table created by Entity Framework code precedence.

Notice how the table structure of the movies table is mapped to the movie class you created earlier? Entity Framework Code gives you the automatic creation of a table structure based on the movie class for you.

When you have completed the operation, right-click moviedbcontext and select Close connection to close the database connection. (If you do not close the connection, an error may occur the next time you run the project.)

Now you can display data from a database in a simple list page. In the next tutorial, we'll continue to look at other code that the framework automatically generates. and add a Searchindex method and Searchindex view so that you can search for a movie in the database.

Related Article

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.