2013-02-25 98 views
1

我有一個網頁一個大GridView,並綁定到一列的HyperLinkfield,有兩個參數,格式如下:爲什麼HyperLinkField會替換某些URL中的字段而不是其他字段?

<asp:HyperLinkField DataNavigateUrlFields="id,nome" DataNavigateUrlFormatString="~/adm/Clipping/Publicidade/Cadastro/ValorPrograma.aspx?programa={0}&amp;nome={1}" HeaderText="Valores" InsertVisible="False" NavigateUrl="~/adm/Clipping/Publicidade/Cadastro/ValorPrograma.aspx"     Text="Ajustar valores"> 
     <ItemStyle ForeColor="#339933" /> 
</asp:HyperLinkField> 

字符串DataNavigateUrlFormatString="~/adm/Clipping/Publicidade/Cadastro/ValorPrograma.aspx?programa={0}&amp;nome={1}DataNavigateUrlFields="id,nome"取代。 對於某些行,一切正常 ...。另一方面,值不會被替換,並且URL不完整。

因此,我去了數據庫,檢查是否有一些數據不一致,並從GridView和另一個不被替換的字段中正常替換字段的數據。

Data is consistent in database. Result 1 isn't being replaced at all when formink the hyperlinkfield

任何想法?

+1

如何對數據庫字符串進行Url編碼? – Hanno 2013-02-25 14:36:08

+0

有沒有辦法做到這一點在網格內,或者我需要一個事件掛鉤? – marquito 2013-02-25 14:37:41

+0

但我看不到任何相關的原因。 – marquito 2013-02-25 14:38:45

回答

0

我同意Hanno's聲明in the comments,這很可能是由於invlaid URL字符造成的。

這是你可以編碼從RowDataBound事件的字符的一種方法:

protected void yourGridView_RowDataBound(Object sender, GridViewRowEventArgs e) 
{ 
    if(e.Row.RowType == DataControlRowType.DataRow) 
    { 
     i = 0; // the ordinal of the column you need to encode 

     DataRowView rowView = (DataRowView)e.Row.DataItem; 
     string id = Server.UrlEncode(rowView["id"].ToString()); 
     string nome = Server.UrlEncode(rowView["nome"].ToString()); 

     string newURL = String.Format("~/adm/Clipping/Publicidade/Cadastro/ValorPrograma.aspx?programa={0}&amp;nome={1}", id, nome); 

     e.Row.Cells[i].Text = newURL; 
    } 
} 

你必須標記像這樣爲你GridView,爲了把它掛到事件處理程序:

OnRowDataBound="yourGridView_RowDataBound" 
+0

我在C#中發佈了我的答案,因爲我沒有看到您指定了一種語言。如果您使用的是VB.NET,則迴應類似,但請告知我是否需要幫助翻譯它。 – jadarnel27 2013-02-25 16:12:19

+0

我正在使用C#,但您的答案對我無效。它給了我一個「Server.UrlEncode(rowView [」id「] .ToString());」的對象引用未設置「,可能是因爲rowView對象爲空(無法調試,因爲它是一個生產系統) 。請注意,我已經對其進行了必要的更改,但可能錯過了某些內容。 – marquito 2013-02-26 13:04:39

+0

發現了這個問題,這確實是一個編碼問題(具體來說就是URL上的':'字符串,但我的方法不同,我更喜歡使用HyperlinkField作爲TemplateField來組成aspx頁面上的URL, @jadarnel27的例子並不適用於我,我會接受你的答案,因爲它有問題,但解決方案需要改進。 – marquito 2013-02-26 13:08:05

2

Hanno建議的comments和由jadarnel27回答的實際Reply,該問題與URL的字符編碼(特別是在這種情況下,第e編碼的:字符)。

爲了解決這個問題,我建議使用TemplateField代替HyperLink場,

 <asp:TemplateField HeaderText="Valores" InsertVisible="False"> 
      <ItemTemplate> 
       <asp:HyperLink ID="HyperLink1" runat="server" 
        NavigateUrl='<%# "~/adm/Clipping/Publicidade/Cadastro/ValorPrograma.aspx?programa=" + HttpUtility.UrlEncode(Eval("id").ToString()) + "&nome=" + HttpUtility.UrlEncode(Eval("nome").ToString()) %>' 
        Text="Ajustar valores"></asp:HyperLink> 
      </ItemTemplate> 
      <ItemStyle ForeColor="#339933" /> 
     </asp:TemplateField> 

的關鍵概念是在模板本身使用HttpUtility.UrlEncode()而不是調用RowDataBound事件如下。

完成之後,數據庫數據將在編寫URL之前正確編碼,並且它正常工作。

+0

我同意這是解決問題的一種更簡潔的方式。我會牢記這一點! – Hanno 2013-02-28 16:00:41

相關問題