2011-11-28 71 views
0

我是ASP.NET MVC3的新手,並拼命地嘗試着簡單地工作。我覺得我正在嘗試做一些非常簡單的事情。但是,我無法獲得一個基本的網格。我使用Visual Studio中的默認設置,這裏是我做了什麼:在MVC3中使用WebGrid

HomeController.cs

public class HomeController : Controller 
{ 
    public ActionResult Index() 
    { 
     ViewBag.Message = "Welcome to ASP.NET MVC!"; 

     List<Person> test = new List<Person>(); 
     test.Add(new Person("John", "Smith")); 
     test.Add(new Person("Bill", "Torr")); 

     return View(test); 
    } 

    public ActionResult About() 
    { 
     return View(); 
    } 
} 

public class Person 
{ 
    public string FirstName { get; set; } 
    public string LastName { get; set; } 

    public Person(string firstName, string lastName) 
    { 
     this.FirstName = firstName; 
     this.LastName = lastName; 
    } 
} 

Index.cshtml @ { ViewBag.Title =「主頁」; }

<h2>@ViewBag.Message</h2> 
<p> 
@{ 
    var grid = new WebGrid(@Model); 
    grid.GetHtml();  
} 
</p> 

奇怪的是,沒有被打印出來了的WebGrid。我期待着兩排。相反,我什麼也沒得到。我究竟做錯了什麼?

回答

1

您忘記強制輸入視圖並將GetHtml方法的結果輸出到視圖輸出流。在這裏你去:

@model IEnumerable<Person> 

<h2>@ViewBag.Message</h2> 
@{ 
    var grid = new WebGrid(Model); 
} 

<p>@grid.GetHtml()</p> 

通知的@grid.GetHtml()是如何從代碼段是什麼基本上寫電網HTML輸出流外化。在你的例子中,你在代碼段中調用了grid.GetHtml(),但是你沒有對結果做任何事情,比如輸出結果。這就是他們被遺忘的原因。

+0

但我不能在.cshtml文件中引用的人。如果我嘗試@model IEnumerable 什麼也沒有顯示。 – Villager

+0

@Villager,當然你可以參考它。只需提供完整的命名空間'@model IEnumerable '。甚至更好,這個命名空間添加到你的'〜/查看/ web.config'文件的''部分,這樣你就不必在所有的意見都做一遍。 –

+0

沒關係。得到它了。謝謝。 – Villager