Learning ASP. NET MVC5 Official Tutorials Summary (vi) access to the model's data through the controller

Source: Internet
Author: User
Tags table definition actionlink


Learning ASP. NET MVC5 Official Tutorials Summary (vi) access to the model's data through the controller


In this chapter, we will create a new Moviescontroller controller , write the code to get the movie data, and use the view template to present the data in the browser.



Before you proceed to the next step, you need to compile the application, otherwise you will get an error when adding the controller.



In Solution Explorer, right-click the Controllers folder and choose add > New Scaffolding Item :








in the add bracket dialog box, select the MVC 5 controller that contains the view (using En), and then click Add button.





Enter Moviescontroller in the controller name input box . In the model class selection list, select Movie (mvcmovie.models). In the data class selection list, select moviedbcontext (mvcmovie.models) .







After clicking the " add " button , vs will create the following files and folders:



· The MoviesController.cs file was created in the Controllers folder



· created the Movies folder in the Views folder



· The create.cshtml, delete.cshtml, details.cshtml, edit.cshtml, and index.cshtml view files are created in the Views\movies folder.



ASP. NET MVC 5 automatically creates a CRUD(create, read, update, delete) Action method and creates a view for them.



You now have a full-featured app that you can use to create, list, edit, and delete movies.



Run the application and view the address http://localhost:xxxxx/Movies in the browser. Because the program relies on the default route, the address requested by the browser is assigned to the Moviescontroller's Index method.



In other words, the browser request Http://localhost:xxxxx/Movies address is equivalent to requesting the Http://localhost:xxxxx/Movies/Index address. An empty movie list is displayed in the browser because we haven't added it yet.




Select the "create New" link, enter some movie information in the open page, and then click the "create" button :






Clicking the "Create" button submits the data to the server and the server passes the movie information to the database. Look at the/movies address again and you'll see our newly added movie in the list.






Open the file Controllers\moviescontroller, and check the generated Index method. Part of the code for Moviescontroller that contains the index method is as follows:


private MovieDBContext db = new MovieDBContext();

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



In the Moviecontroller class, an instance of the Moviedbcontext class is included, which you can use to query, edit, and delete movies.



The Moviescontroller index method returns the movie data from all databases and then passes the result to the index view.



ASP. NET MVC also provides the ability to pass strongly typed data or object-to-view. This strongly-typed approach provides better compile-time checking and richer IntelliSense,and the scaffolding mechanism inVisual Studio uses this approach when creating Moviescontroller classes and views.



Examine the Details method in the Controllers\moviescontroller.cs file, and here is some of the code for the Detais method:


public ActionResult Details(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Movie movie = db.Movies.Find(id);
            if (movie == null)
            {
                return HttpNotFound();
            }
            return View(movie);
        }



The ID can be passed to the controller by route data or query string.



If a movie message is found, a movie's model is passed to the details view. Check the contents of the views\movies\details.cshtml file.



With the @model statement at the top of the file, you know what type of object this view expects. When you create a movie controller,Visual Studio will automatically include the following statement at the top of the details.cshtml file:


@model MvcMovie.Models.Movie


       @model   directives allow the use of strongly typed  Model  Object access to the movie object passed from  Controller  to  View  (note that at this point the model movie  type). For example, in the details.cshtml   template, the code will movie The model  object is passed to displaynamefor   and  displayfor html Help method. The Create and  Edit  methods also pass a model to the view, there is no more talk here.



Check the Index method of the index.cshtml template and the MoviesController.cs file , The program first creates a list object for the good one movie model, and then passes the created List object through the view method to the views:


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


Visual Studio automatically adds a @model statement at the top of the index.cshtml file:


@model ienumerable<mvcmovie.models.movie>


The @model directive allows the use of strongly typed model objects to access the movie list object passed to View from the Controller (note that the model object at this time is the ienumerable<movie> type). For example, in the index.cshtml template, the code loops through the foreach statement for each movie object in the strongly typed Model.


@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 ienumerable<movie item  objects are all  Movie  types. This means that your code has better compile-time checking and full IntelliSense support.



The Entity Framework Code first checks whether the database used by the connection string exists, and if it does not, automatically creates the database file. You can see if the database is created under the App_Data folder (if you don't see the Movies.mdf file, click the Show All Files button on the Solution Explorer toolbar , Click the refresh button, and then expand the App_Data folder.






Double-click the Movies.mdf file, open Server Explorer, and then expand Tables directory View Movies data Tables .






Right- Movies The table and select " Open Table definition "to view the Entity Framework Code First the table structure created for us.



Right- Movies The table and select " Show Table Data " to view the movie data we created.



Entity Framework Code First automatically creates a table structure, including field names and data types, based on our Movie class.



After we have finished viewing or editing the database, to close the connection in Server Explorer, right-Moviedbcontext, select " close connection ". (If you don't close the connection, you may get an error The next time you run the program).



This chapter is about here, and the next chapter we'll talk about the edit view code.


















Learning ASP. NET MVC5 Official Tutorials Summary (vi) access to the model's data through 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: 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.