ASP. MVC4 Getting Started Guide (5): Accessing the data model from the controller

Source: Internet
Author: User
Tags actionlink visual studio 2010

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

Build the application (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 build succeeds, the following options appear. Set the following options:

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

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

· Model class: Movie (Mvcmovie.models).

· Data Context class: Moviedbcontext (Mvcmovie.models).

· Views: 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 Auto-created action methods and view files are called infrastructure files). Now you have the ability to create, list, edit, and delete all of the web features of the movie entity.

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

Create a movie

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

Clicking the Create button will cause the form to be submitted to the server, and the movie information will be saved to the database, and you will be 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.

Take a look at the generated code

Open the Controllers\moviescontroller.cs file, and locate the generated index method. A part of the movie controller and the index method are shown below.

 Public class moviescontroller:controller{    privatenew  moviedbcontext ();     //    // GET:/movies/     Public actionresult Index ()    {        return  View (db. Movies.tolist ());    }

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

Private Moviedbcontext db = new Moviedbcontext ();

Requests 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 the use of 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 typing makes it 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 details method of the build in the Controllers\moviescontroller.cs file. The details method in the movie controller is shown below.

 Public ActionResult Details (int0) {     = db. Movies.find (ID);      if NULL )     {         return  httpnotfound ();     }      return View (movie);}

If you find an instance of a Movie,movie model, 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 object type 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. The Create and edit methods also have a strongly typed model object in which the view template is passing the movie.

Take a look at the index method in the Index.cshtml view template and the MoviesController.cs. Notice how the code creates a 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<>

This @model declaration allows the controller to pass a strongly typed movie list model object to the view view. For example, in a index.cshtml template, use a foreach statement on a strongly typed model object to iterate through the movie list:

@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 {}) |             @Html. ActionLink ("Details", "Details", {}) | @Html. ActionLink ("delete", "delete", {})</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 benefit is that this means that you can check the code at compile time and support 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 it detects that a database connection string does not exist pointing to the movies database. Look in the App_Data folder and you can verify that it has been created. If you do not 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 Database Explorer, and then expand the Tables folder to view the movie table.

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

Note: If you use VWD or Visual Studio 2010, you may see an error message that resembles 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 of 655 and earlier versions. Unable to downgrade support.

· "InvalidOperation Exception was unhandled by user code" provided the SqlConnection did not specify the initial database.

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

Right-click the Movies table and select Show 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 the Entity Framework code precedence.

Notice how you can map the table structure of the movies table to the movie class that you created earlier? The Entity Framework code takes precedence for you to automatically create a table structure based on the movie class.

When you are finished, select close connection to close the database connection by right-clicking Moviedbcontext. (If you do not close the connection, an error may occur the next time you run the project).

Now you can display the data in the database in a simple list page. In the next tutorial, we will 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 movies in the database .

full document Download: ASP. NET MVC4 Getting Started Guide. pdf

--------------------------------------------------------------------------------------------------------------- -----

Translator Note:

This series of 9 articles, translated from the official ASP. NET MVC4 tutorial, because this series of articles concise, space moderate, from an example to explain, the full text finally completed a small system to manage the film, very suitable for the novice MVC4 ASP, and start the development work. 9 Articles for:

1. Introduction to ASP. MVC4

• Original address:

• Translation Address:

2. Add a Controller

• Original address: Http://

• Translation Address:

3. Add a View

• Original address: Http://

• Translation Address:

4. Add a model

• Original address: Http://

• Translation Address:

5. Accessing the data model from the controller

• Original address: Accessing-your-models-data-from-a-controller

• Translation Address:

6. Validating editing methods and editing views

• Original address: Http://

• Translation Address:

7. Add a new field to the movie table and model

• Original address: Adding-a-new-field-to-the-movie-model-and-table

• Translation Address:

8. Adding a validator to the data model

• Original address: Http://

• Translation Address:

9. Query details and delete records

• Original address: Http://

• Translation Address:

10. Third-party control Studio for ASP. Wijmo MVC4 Tools App

• Address:

ASP. MVC4 Getting Started Guide (5): Accessing the data model from the controller

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: 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.