[Official tutorial] Asp. Net MVC4 Getting Started Guide (5): Access data models from controllers, mvc4 Getting Started Guide

Source: Internet
Author: User
Tags actionlink

[Official tutorial] Asp. Net MVC4 Getting Started Guide (5): Access data models from controllers, mvc4 Getting Started Guide

In this section, you create a newMoviesControllerClass, and write code in the Controller class to obtain the movie data, and use the view template to display the data in the browser.

Before starting the next step, Build the application (Generate an application)(Ensure that the Application compilation is correct)

 

Right-click the Controller folder and create a newMoviesControllerController. After the Build is successful, the following options are displayed. Set the following options:

· Controller Name:MoviesController. (This is the default value ).

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

· Model class:Movie (MvcMovie. Models).

· Data context:MovieDBContext (MvcMovie. Models).

· Opinions:Razor (CSHTML ).(Default ).

 

ClickAdd. Visual Studio Express creates the following files and folders:

· MoviesController. cs file in the project controller folder.

· Movie folder under the project view folder.

· 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) operation methods, and related view files (CRUD automatically creates operation methods and view files are called infrastructure files ). Now you have all the Web functions to create, list, edit, and delete movie Entity.

Run the application and append/Movies to the URL of the browser address bar to browse the Movies controller. Because the application depends on the default route (Global. asaxFile), browser requestHttp: // localhost: xxxxx/MoviesWill be routedMoviesDefault ControllerIndexOperation Method. In other words, browser requestsHttp: // localhost: xxxxx/MoviesEquivalent to browser requestsHttp: // localhost: xxxxx/Movies/Index. Because you have not added any content, the result is an empty movie list.

Create a movie

ClickCreate NewLink. Enter details about the movie, and then clickCreateButton.

ClickCreateThe button will make the form submitted to the server, and the movie information will be saved to the database. Then you will be redirected to URL/Movies. You can see the new movie you just created in the list.

Create more movie data. You can also clickEdit,DetailsAndDeleteFunction link.

Let's take a look at the generated code.

OpenControllers \ MoviesController. csFile, and find the generatedIndexMethod. A part of movie controllers andIndexThe method is as follows.

public class MoviesController : Controller{    private MovieDBContext db = new MovieDBContext();    //    // GET: /Movies/    public ActionResult Index()    {        return View(db.Movies.ToList());    }

 

Below isMoviesControllerClass to instantiate the context instance of the Movie Database, as described above. The Movie Database context instance can be used to query, edit, and delete movies.

private MovieDBContext db = new MovieDBContext();

 

DirectionMoviesController request to returnMoviesAll records in the movie database table, and then pass the resultsIndexView.

Strong model and @ model keywords

In the previous tutorials of this series, you can see thatViewBagObject To pass data or objects from the Controller to the view template.ViewBagIt is a dynamic object and provides a convenient post-binding method to pass information to the view.

ASP. net mvc also provides the ability to transmit strong data or objects to view templates. This strong type makes it easier to check your code during compilation and provides richer intelligent awareness in the Visual Studio editor. When creating operation methods and views, the infrastructure mechanism in Visual Studio usesMoviesControllerClass and view template.

InControllers \ MoviesController. csFile to see the generatedDetailsMethod. In the movie controllerDetailsThe method is as follows.

public ActionResult Details(int id = 0){     Movie movie = db.Movies.Find(id);     if (movie == null)     {         return HttpNotFound();     }     return View(movie);}

 

IfMovie,MovieThe instance of the model is passed to the Detail View. Take a lookViews \ Movies \ Details. cshtmlFile.

By introducing@modelStatement, you can specify the expected object type of the view. When you create a movie controller, Visual Studio@modelThe statement is automatically included inDetails. cshtmlFile top:

@ Model MvcMovie. Models. Movie

This@modelThe statement allows the ControllerModelThe object is passed to the View, so that you can access the passed strong-type movie Model in the View. For exampleDetails. cshtmlTemplate,DisplayNameForAnd DisplayFor HTML HelperModelEach field of a movie is transmitted. Both the creation and editing methods and view templates are passing strong Model Objects of movies.

Take a lookIndex. cshtmlView templates andMoviesController. csInIndexMethod. Note how the codendexIn the operation method, createListObject and callViewMethod.

This code is passed in the ControllerMoviesList to view:

public ActionResult Index(){     return View(db.Movies.ToList());}

 

When you create a movie controller, Visual Studio Express automatically includes@modelStatementIndex. cshtmlFile top:

@ Model IEnumerable <MvcMovie. Models. Movie>

This@modelThe Declaration allows the Controller to set a list of strongly typed moviesModelThe object is passed to the View. For exampleIndex. cshtmlIn the templateModelObject usageforeachThe statement traverses the movie list cyclically:

@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>}

 

BecauseModelThe object is strongly typed (YesIEnumerable<Movie>Object), so everyitemThe object type isMovieType. One of the benefits is that this means you can check the code during compilation and support more comprehensive intelligent awareness in the Code Editor:

Use SQL Server LocalDB

The Entity Framework Code First Code takes precedence. If no database connection string pointsMoviesThe database is automatically created. Find it in the App_Data folder and verify that it has been created. If you cannot seeMovies. mdfFileSolution Resource ManagerOn the toolbar, clickShow all filesClickRefreshAnd expand the App_Data folder.

Double-clickMovies. mdfOpenDatabase Resource Manager, And then expandTableFolder to view the movie table.

Note: If the database resource manager is not displayed, you canToolsIn the menu, selectConnect to databaseAnd disableSelect data sourceDialog box. In this way, the database resource manager is forcibly opened.

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

· The database cannot be opened because the database 'C: \ Webs \ MVC4 \ MVCMOVIE \ APP_DATA \ MOVIES. MDF 'is of version 706. This server supports databases of version 655 and earlier. It cannot be downgraded.

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

You must install the SQL Server data tool and LocalDB. Verify the MovieDBContext connection string specified earlier.

Right-clickMoviesTable and selectShow table dataTo view the data you have created.

Right-clickMoviesTable, selectOpen table definitionView the table structure of the table created by the Entity Framework code first.

Note howMoviesThe table structure of the table is mapped toMovieClass? The Entity Framework code is automatically created based onMovieThe table structure of the class.

After you complete the operation, right-clickMovieDBContext, SelectClose connectionClose the connection to the database. (If you do not close the connection, an error may occur when you run the project next time ).

Now, you can display the data in the database on the simple list page. In the next tutorial, we will continue to look at other code automatically generated by the framework. And addSearchIndexMethod andSearchIndexView, so that you can search for movies in the database. Accessing the data model from the Controller is an important part of MVC data transmission. Only by understanding this part can MVC development be better. Of course, some development tools help the development process. The ComponentOne Studio ASP. net mvc lightweight control greatly improves the work efficiency and reduces the workload.

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.