2015-09-16 32 views
0

所以我想完成的是動態創建一個基於傳遞給函數的附件列表的表。如果我的「供應商」對象具有20個附件列表,我有一個函數可以生成一個表並循環遍歷附件,並將每個文件名放在表格中的新單元格和行中。生成表的函數正常工作,並按預期填充表。但是,當函數從函數返回HtmlTable時,它只會以System.Web.UI.HtmlControls.HtmlTable的形式出現在網頁上。我怎樣才能得到這個函數返回表而不是字符串文字?如何獲取HtmlTable從函數返回以顯示在.cshtml文件中

這是我在Details.cshtml功能

@model EnterpriseServices.Vendor.Vendor 
@using System.Web.UI.HtmlControls 

@{ 
    ViewBag.Title = "Details"; 
    Layout = "~/Views/Shared/_Layout.cshtml"; 
    int incrementer = 1; 
    TagBuilder hrTag = new TagBuilder("hr"); 
    TagBuilder newLineTag = new TagBuilder("br"); 
} 

@functions { 
    public static HtmlTable PopulateTable(IList<EnterpriseServices.Vendor.Attachment> attachments) 
    { 
     HtmlTable table = new HtmlTable(); 

     foreach (var a in attachments) 
     { 
      HtmlTableRow row = new HtmlTableRow(); 
      HtmlTableCell cell = new HtmlTableCell(); 
      cell.InnerText = Path.GetFileName(a.AttachmentPath); 
      row.Cells.Add(cell); 
      table.Rows.Add(row); 
     } 

     return table; 
    } 
} 

這裏是代碼調用Details.cshtml的PopulateTable()函數的部分:

<dt> 
    @Html.DisplayNameFor(model => model.Attachments) 
</dt> 

<dd> 
    @PopulateTable(Model.Attachments) 
</dd> 

這裏是什麼樣子在網頁上: enter image description here

+1

您不能在MVC或Razor中使用WebForms控件。您應該用簡單的Razor HTML塊代替該代碼。 – SLaks

回答

0

您不能在MVC或Razor中使用WebForms控件。

相反,您應該用Razor helper替換該代碼,將<tr><td>標記嵌入到循環中。

+0

我是與MVC/Razor合作的新手。我不知道剃刀輔助者是什麼,但我現在要去查看它。謝謝。 –

+0

這工作。我將該功能更改爲內嵌和​​標籤的剃刀幫手,它的工作完美。 –

0

SLaks使用剃刀助手是正確的。這裏是工作的剃刀幫手,剃刀幫手發佈供大家參考:

@helper PopulateTable(IList<EnterpriseServices.Vendor.Attachment> attachments) 
{ 
    <table> 
     @foreach (var a in attachments) 
     { 
     <tr> 
      <td> 
       <a href="@a.AttachmentPath">@Path.GetFileName(a.AttachmentPath)</a> 
      </td> 
     </tr> 
     } 
    </table> 
} 
+0

你的'href'是錯的;你可以簡單地寫'href =「@a.AttachmentPath」'並去掉變量。 – SLaks

+0

我已編輯帖子。 –

相關問題