2013-12-20 18 views
0

我是ASP.NET MVC的新手。我需要創建一個動作結果來顯示我的列表的內容。如何添加動作結果? mvc5

我在Movie.cs類下面的代碼。我需要幫助創建操作結果。我的代碼是:

namespace MvcMovie.Models 
{ 
    public class Movie 
    { 
    public int ID { get; set; } 
    public string Title { get; set; } 
    public DateTime ReleaseDate { get; set; } 
    public string Genre { get; set; } 
    public decimal Price { get; set; } 
    } 

public class MovieDBContext : DbContext 
{  
    public List<Movie> GetMoviesList() 
    { 

     List<Movie> lmovie = new List<Movie>(); 

     SqlConnection con = new SqlConnection("Data Source=dev01;Initial Catalog=Test;Integrated Security=True"); 
     con.Open(); 
     SqlCommand cmd = new SqlCommand("select * from Movies", con); 

     SqlDataReader dr = cmd.ExecuteReader(); 
     DataTable dt = new DataTable(); 
     dt.Load(dr); 
     con.Close(); 


     foreach (DataRow r in dt.Rows) 
     { 
      Movie mv = new Movie(); 
      mv.ID = Convert.ToInt32(r["ID"]); 
      mv.Title = r["Title"].ToString(); 
      mv.Price = Convert.ToInt32(r["Price"]); 
      mv.ReleaseDate = Convert.ToDateTime(r["ReleaseDate"]); 
      mv.Genre = r["Genre"].ToString(); 
      lmovie.Add(mv); 

     } 
     return lmovie; 
    } 

} 
} 

這是我行動的結果在MoviesController:

public ActionResult Index() 
{ 
    return View(-----); 
} 
+0

試試閱讀以瞭解Asp.Net MVC的基礎 - > http://www.asp.net/mvc/tutorials/mvc-5/introduction/getting-started並讓我知道 –

回答

0

實例化你在你的控制器的DataContext並將結果返回到您的視圖,以便你可以去代表他們。

MoviesController:

public ActionResult Index(){ 
    var context = new MovieDBContext(); 
    var allMovies = context.GetMoviesList(); 
    return View(allMovies); 
    } 

與剃刀觀點默認行爲啓用:這將搜索在/查看/電影文件夾視圖文件「Index.cshtml」。您可以使用List的模型創建index.Cshtml,以便您可以在視圖中使用'Model'作爲列表迭代器。

但是;去閱讀任何有關C#/ MVC的入門教程,它應該會給你一個更好的想法。 http://www.asp.net/mvc/tutorials/mvc-5/introduction/getting-started

+0

我試過了代碼,我得到此錯誤: 傳遞到詞典中的模型項的類型爲「System.Collections.Generic.List'1 [MvcMovie.Models.Movie]」,但是這需要字典類型「MvcMovie.Models.Movie」 – Linkz

+0

的模型項這意味着你的視圖'Index.cshtml'期待一個不同的模型(電影),而不是他得到的 - 一個電影列表。 –

+0

非常感謝 – Linkz

0
public ActionResult Index()  
{ 
    var dbContext = new MovieDBContext(); 
    var movieList= dbContext .GetMoviesList(); 
    return View(movieList); 
} 

確保您的索引視圖(index.cshtml)是強類型到Movie

@model List<MvcMovie.Models.Movie> 
@foreach(var item in Model) 
{ 
    <h2>@item.Title</h2> 
} 

注意的集合:你繼承DBContext類來創建你的MovieDBContext你有你GetMoviesList方法。但在該方法中,您正在使用典型的ADO.NET代碼來獲取數據。在這種情況下,你甚至不需要從DBContext繼承你的課程。

如果從繼承的DbContext,您可以使用實體框架來獲取數據,而無需編寫代碼的那些行。在互聯網上籤出一些實體框架教程,看看它是如何工作的。