2012-03-22 38 views
1

我是asp.net Mvc的初学者。我尝试做一些练习来学习它。我在这个环节的样品:http://weblogs.asp.net/scottgu/archive/2007/12/06/asp-net-mvc-framework-part-3-passing-viewdata-from-controllers-to-views.aspx如何使用MVC 3 aspx引擎中的方法以及如何在mvc 3中使用Repeater控件?

我犯同样的样品使用此链接:如果您

namespace MvcAppExtNet.Controllers 
{ 
    public class ProductController : Controller 
    { 
     // 
     // GET: /Product/ 

     public void GetProduct() 
     { 
      List<Products> list = new List<Products>() { 
       new Products() { Id = 1, Name = "Hıyar" }, 
       new Products() { Id = 2, Name = "Kereviz" } }; 

      ViewData["Products"] = list; 
     } 

    } 
} 

enter image description here

我的观点:


<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" CodeBehind="~/Views/Product/ListProducts.aspx.cs" AutoEventWireup="true" Inherits="MvcAppExtNet.Views.Product.ListProducts" %> 

<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server"> 
    ListProducts 
</asp:Content> 

<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server"> 

<h2>ListProducts</h2> 


</asp:Content> 

<asp:Content ID="Content3" ContentPlaceHolderID="head" runat="server"> 
</asp:Content> 

<asp:Content ID="Content4" ContentPlaceHolderID="ContentPlaceHolder2" runat="server"> 
<asp:Repeater ID="ProductList" runat="server"> 
<ItemTemplate> 
<li> 
<%#Eval("Name") %> 
</li> 
</ItemTemplate> 
</asp:Repeater> 
</asp:Content> 

我的控制器看看ListProducts.aspx.cs:

enter image description here

怎么看我的Repeater控件(产品列表是一种中继!!!!)在C#代码?另外如何使用方法(不使用ActionResult)?非常感谢。

+2

asp.net MVC不是asp。net webforms,以类似于中继器的方式呈现数据,您可以在视图文件中编写一个'foreach'。 – Matthew 2012-03-22 13:08:14

+1

MVC中没有数据绑定或服务器控件,这种方式真的更好。在MVC中,您将视图模型传递给视图,并在那里编写“显示逻辑”。我建议你在使用它来完成任何真实项目之前,先通过Asp.Net MVC的基础知识。 – 2012-03-22 13:12:38

回答

2

这个问题被标记在ASP.NET MVC3,所以我打算这样回答。

请继续阅读http://www.asp.net/mvc上的许多教程。这真是一个令人兴奋的框架,我更喜欢它的网页形式。从MVC3开始。

它应该完成的方式是控制器通过执行存储库调用从数据库获取产品的列表。控制器将这个产品列表传递给视图。该视图将呈现它。基本上,这是我会怎么做:

产品类:

public class Product 
{ 
    public int Id { get; set; } 
    public string Name { get; set; } 
} 

我的视图模型:

public class ProductListViewModel 
{ 
    IEnumerable<Product> Products { get; set; } 
} 

在我控制我的操作方法我做一个数据库调用返回的产品。然后,我实例化一个新的视图模型对象和属性设置的产品到从数据库返回的名单:

public ActionResult List() 
{ 
    ProductListViewModel viewModel = new ProductListViewModel 
    { 
      Products = productRepository.GetAllProducts() 
    }; 

    return View(viewModel); 
} 

在我看来,我有以下几点:

<table> 

@foreach(Product product in Model.Products) 
{ 
    <tr> 
      <td>Product Name:</td> 
      <td>product.Name</td> 
    </tr> 
} 

</table> 

我希望我已经为你清理了一些东西。这只是一个指南,使用它并相应地修改它。

3

MVC的工作方式与Web表单有所不同。您不要在视图中使用控件,并且MVC不具有中继控件。它有模型绑定和Razor,可以让你更加控制。

随着阅读的一点点,你应该尽快找到你的头。我建议你开始here

好运

3

MVC 3不具有控制和视图状态。如果你问这个问题,那么你错过了一些有关MVC模式的基本知识,因此我建议你通过教程工作http://www.asp.net/mvc