2011-07-28 63 views
0

我指的例子之一,並在它的aspx頁面,這個代碼寫的是:如何擺脫Asp.Net MVC中每個循環的命名空間?

<% foreach (KandaAlpha.Domain.Model.Entities.Customer customer in (List<KandaAlpha.Domain.Model.Entities.Customer>)(ViewData["Customers"])) 
     { %> 
    <tr> 
     <td> 
      <%= customer.CustomerID%> 
     </td> 
     <td> 
      <%=customer.FullName%> 
     </td> 
     <td> 
      <%=customer.LastUpdatedOn.ToString()%> 
     </td>   
    </tr> 
    <% } %> 

我怎麼能寫KandaAlpha.Domain.Model.Entities.Customer只是客戶?我應該在哪裏編寫導入命名空間代碼?

感謝提前:)

回答

4

通過在您的視圖的開頭使用<%@ Import聲明:

<%@ Import Namespace="KandaAlpha.Domain.Model.Entities" %> 

,或者是附加的命名空間,以你的web.config的<namespaces>部分,在這種情況下,它將是全球所有意見:

<pages> 
    <namespaces> 
    <add namespace="System.Web.Helpers" /> 
    <add namespace="System.Web.Mvc" /> 
    <add namespace="System.Web.Mvc.Ajax" /> 
    <add namespace="System.Web.Mvc.Html" /> 
    <add namespace="System.Web.Routing" /> 
    <add namespace="KandaAlpha.Domain.Model.Entities"/> 
    </namespaces> 
</pages> 

或者最好的方式,我會推薦你​​的是擺脫ViewData和你的查看模型和顯示模板。在這種情況下整個foreach環路將消失,將通過下面的一個襯裏取代:

<table> 
    <%= Html.DisplayFor(x => x.Customers) %> 
</table> 

,然後將相應的顯示模板(~/Views/Shared/DisplayTemplates/Customer.ascx)定義將被渲染的每個元件的顧客的模板內您的視圖模型的Customers集合:

<%@ Control 
    Language="C#" 
    Inherits="System.Web.Mvc.ViewUserControl<Customer>" 
%> 
<tr> 
    <td><%= Html.DisplayFor(x => x.CustomerID) %></td> 
    <td><%= Html.DisplayFor(x => x.FullName) %></td> 
    <td><%= Html.DisplayFor(x => x.LastUpdatedOn) %></td> 
</tr> 

還要注意的Html.DisplayFor的使用,因爲如果您的客戶全名是<script>alert('I hacked you');</script>你可能會遇到麻煩,你沒有HTML編碼它。

正如你可以看到一旦我們擺脫ViewData並開始使用視圖模型,這是我總是建議我們的意見變得非常簡單和可讀。

+0

這是一個特殊的文件夾:'〜/ Views/Shared/DisplayTemplates /'?像其他魔術文件夾一樣,即控制器,模型等? – Jaggu

+1

@Bob:是的,它是基於約定的。你可以在那裏有顯示模板,或者在〜/ Views/YourController/DisplayTemplates /中,並且編輯器模板也有相同的約定(只需在任何地方切換「顯示」爲「編輯器」...) –

+1

@Bob Lee Swagger,yes it是特別的。你也可以使用'〜/ Views/YourControllerName/DisplayTemplates',這是ASP.NET MVC首先查找模板的地方,如果它沒有找到它,它將轉到Shared文件夾。對於僅對給定控制器有效的模板可能很有用。 –

0
<%@ Page Title="" Language="C#" MasterPageFile="~/Themes/Whatever/Site.Master" Inherits="System.Web.Mvc.ViewPage<Whatever.ViewModels.MyViewModel>" %> 
<%@ Import Namespace="KandaAlpha.Domain.Model.Entities" %> 
<%= //content %>