2012-07-07 67 views

回答

21

我該如何做到這一點?

很簡單。答案如asp.net-mvc中99.99%的問題總是相同:使用查看模型

我假設你有以下的域模型:

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

,以便始終通過定義,這將滿足這一觀點被分組列表,你要實現的要求(視圖模型開始通過他們的財產Name的第一個字母,並顯示一個鏈接Tag域模型):

public class TagViewModel 
{ 
    public string Letter { get; set; } 
    public IEnumerable<Tag> Tags { get; set; } 
} 

那麼你顯然有一個控制器,其職責是爲了獲取域米到查詢您的DAL層Odel等,建立一個視圖模型並最終通過這個視圖模型的視圖:

public class HomeController : Controller 
{ 
    public ActionResult Index() 
    { 
     // Get the domain model 
     var tags = new[] 
     { 
      // Guess this comes from a database or something 
      new Tag { Id = 1, Name = "Apple" }, 
      new Tag { Id = 2, Name = "Ant" }, 
      new Tag { Id = 3, Name = "Car" }, 
      new Tag { Id = 4, Name = "Sky" }, 
      new Tag { Id = 5, Name = "Sea" }, 
      new Tag { Id = 6, Name = "Sun" }, 
     }; 

     // now build the view model: 
     var model = tags.GroupBy(t => t.Name.Substring(0, 1)).Select(g => new TagViewModel 
     { 
      Letter = g.Key, 
      Tags = g 
     }); 

     return View(model); 
    } 
} 

和最後一個視圖:

@model IEnumerable<TagViewModel> 

@foreach (var item in Model) 
{ 
    <h2>@item.Letter</h2> 
    <ul> 
     @foreach (var tag in item.Tags) 
     { 
      <li> 
       <!-- Please notice the usage of an HTML helper to generate 
        the anchor instead of the hardcoded url shown in your 
        question which is very bad 
       --> 
       @Html.ActionLink(
        tag.Name, 
        "Post", 
        "Tag", 
        new { id = tag.Id }, 
        null 
       ) 
      </li> 
     } 
    </ul> 
} 

這顯然會得到所需的結果:

enter image description here

因此,下次您在ASP.NET MVC中遇到一些困難或問題時請告訴自己:我必須使用視圖模型。看,問題解決了。

+1

非常感謝您的好回答....! :) – Nalaka526 2012-07-08 02:10:34

相關問題