`
suizhikuo
  • 浏览: 28926 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

ASP.NET MVC 3 (Accessing your Model's Data from a Controller) (5/9)

 
阅读更多

Accessing your Model's Data from a Controller

In this section, you'll create a new MoviesController class and write code that retrieves the movie data and displays it in the browser using a view template.

Right-click the Controllers folder and make a new MoviesController class.

This creates a new MoviesController.cs file in the project's Controllers folder. Let's update the Index action method in the MoviesController class so that is retrieves the list of movies. Don't forget to include a using statement for the MvcMovie.Models namespace.

using System;
using System.Linq;
using System.Web.Mvc;

using MvcMovie.Models; // Required in order to access MovieDBContext.

namespace MvcMovie.Controllers 
{
  public class MoviesController : Controller 
  {
    MovieDBContext db = new MovieDBContext();

    public ActionResult Index() {
      var movies = from m in db.Movies
            where m.ReleaseDate > new DateTime(1984, 6, 1)
            select m;

      return View(movies.ToList());
    }
  }
}

The code is performing a LINQ query to retrieve only movies that were released after the summer of 1984. We'll need a view template to render this list of movies, so right-click inside the method and select Add View to create it.

In the Add View dialog box, we'll indicate that we're passing a Movie class to the view template. Unlike the previous times when we used the Add View dialog box and chose to create an empty template, this time we'll indicate that we want Visual Web Developer to automatically "scaffold" a view template for us that contains some default content. To do this, select List in the Scaffold template drop-down list.

Remember that after you've created a new class, you'll need to compile your application before the class shows up in the Add View dialog box.

Click Add. Visual Web Developer automatically generates the code for a view that displays our list of movies. This is a good time to change the <h2> heading to something like "My Movie List" like you did earlier with the "Hello World" view.

The code below show a portion of the Index view for the movie controller. In this section, change the format string for the release date from {0:g} to {0:d} (that is, from general date to short date). Change the format string for the Price property from {0:F} to {0:c} (from float to currency).

In addition, in the table header, change the column name from "ReleaseDate" to "Release Date" (two words).

<table>
  <tr>
    <th></th>
    <th>Title</th>
    <th>Release Date</th>
    <th>Genre</th>
    <th>Price</th>
    <th>Rating</th>
  </tr>
  @foreach (var item in Model) {
  <tr>
    <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>
    <td>
      @item.Title
    </td>
    <td>
      @String.Format("{0:d}", item.ReleaseDate)
    </td>
    <td>
      @item.Genre
    </td>
    <td>
      @String.Format("{0:c}", item.Price)
    </td>
  </tr>
}
</table>

We have not added a connection string to the Web.config file. When no connection string is provided, the code-first approach creates the database file in the default SQL Express directory and gives the file a name based on the database context name with the namespace prepended. Let's set an explicit connection string now.

Creating a Connection String and Working with SQL Server Express

Open the application root Web.config file. (Not the Web.config file in the Views folder.) The image below show both Web.config files; open the Web.config file circled in red.

Add the following connection string to the <connectionStrings> element in the Web.config file.

  <add name="MovieDBContext"
  connectionString="Server=./SQLEXPRESS;
  Database=Movies;Trusted_Connection=true"
  providerName="System.Data.SqlClient" />

Run the application and browse to the Movies controller by appending /Movies to the URL in the address bar of your browser. An empty list of movies is displayed.

A SQL Server Express 2008 database called Movies was automatically created for you. You can verify that it's been created by looking in the C:/Program Files/Microsoft SQL Server/MSSQL10.SQLEXPRESS/MSSQL/DATA folder.

Under the hood, our code-first approach has created an empty Movies database with a movie table with columns that map to our Movie class. In the next tutorial, we'll add a Create method to add movies to this database.

分享到:
评论

相关推荐

    Professional ASP.NET 3.5 SP1 Edition: In C# and VB(part1)

    Ways to use and extend the Provider Model for accessing data stores, processes, and more * What freeware tools you need in Scott Hanselman's ASP.NET Ultimate Developer Tools appendix

    Programming ASP.NET

    accessing data using the ADO.NET object model, and updating data with or without transaction support. Programming ASP.NET also discusses such advanced topics as: Caching and performance Security ...

    ASP.NET 4 Unleashed(part 1)

    Book Description The most comprehensive book on Microsoft’s new ASP.NET 4, ASP.NET 4 Unleashed covers all facets of ASP.NET development....Construct a complete ASP.NET 4 website from start to finish

    ASP.Net调用摄像头拍照

    3. **ASP.NET后端处理**:在用户拍照后,可能需要将照片上传到服务器。这可以通过发送AJAX请求实现,将base64编码的图片数据传递给ASP.NET的HTTP POST接口。后端接收到数据后,可以将其保存为本地文件或存储到数据库...

    ASP.NET Gridview隐藏/显示列源码

    ASP.NET实现Gridview隐藏/显示列源码 介绍: 这篇文章演示如果让用户有显示/隐藏他们需要的GridView的列的功能,这是非常有用的,因为在GridView的所有列并不是每个的用户都需要的.用户想根据自己的需求看到想要的...

    Professional.ASP.NET.2.0.AJAX

    &lt;br&gt;What you will learn from this book &lt;br&gt;How to create a better user experience by adding more dynamic UIs Steps for accessing ASP.NET profile and authentication services Ways to ...

    Wrox.Beginning.ASP.NET.Security

    - **使用ASP.NET MVC框架进行安全开发(Secure Development with the ASP.NET MVC Framework)**:聚焦于MVC框架下的安全编程实践,包括模型绑定、视图渲染和控制器动作的安全性。 ### 结论 本书全面覆盖了ASP.NET...

    oa源码 大型oa asp.net 源码

    The given source code excerpt represents a portion of an ASP.NET application that handles user authentication for an Office Automation (OA) system. The code is written in C# and utilizes several ...

    Microsoft ASP.NET Programming with Microsoft Visual Basic .NET Version 2003 Step by Step part 2/2

    Appropriate for novice developers with some programming experience, this guide provides instructions for configuring an ASP.NET application, creating web forms, using server controls, accessing data ...

    MCTS 70-516 Accessing Data with Microsoft .NET Framework 4

    MCTS Self-Paced Training Kit (Exam 70-516) Accessing Data with Microsoft .NET Framework 4 eBook.pdf.7z. 請用7zip解壓

    Expert .NET Micro Framework

    Topics like cryptography and encrypted data exchange with a .NET or Compact Framework application are covered. What you’ll learn Describes and compares wireless communication technologies and how ...

    MCTS 70-516 Accessing Data with Microsoft .NET Framework 4 练习1

    MCTS 70-516 Accessing Data with Microsoft .NET Framework 4 练习1。注意,因为我只能上传小于15兆的文件,所以我把setup1.msi给那出去了。安装时需要把setup1.exe放进Practice Tests文件夹。

    C# S7.Net 连接西门子S7PLC

    在本文中,我们将深入探讨如何使用C#编程语言与S7.Net库来连接并通信西门子S7系列的PLC(可编程逻辑控制器)。S7.Net是一个专门为.NET开发者设计的库,允许他们轻松地与西门子S7 PLC进行数据交换,无论是读取输入、...

    Pro WF - Windows Workflow in .NET 4.pdf

    Customizing your workflows * Accessing your workflows in a variety of ways in a variety of situations * Using WF with Web Services and ASP.NET * Integrating WCF and WF Who this book is for This book ...

    显示/隐藏GridView的列源码

    VB.NET - Client-side example accessing data stored in session. 服务端的例子: C#.NET - Server-side example accessing data stored in session. C#.NET - Server-side example which includes: MasterPage...

    Accessing Twain 2_huntermog_vb.net_

    标题中的"Accessing Twain 2_huntermog_vb.net_"表明这是一个关于使用VB.NET访问TWAIN接口的示例项目。TWAIN是一种标准的软件接口,允许应用程序(如图像扫描器或相机)与硬件设备(如扫描仪)进行通信。在VB.NET...

Global site tag (gtag.js) - Google Analytics