2012-11-14 38 views
0

C#新手問,所以如果問題很愚蠢或者答案很明顯,可能是因爲我不完全瞭解XmlDataSource的工作方式。如何引用未綁定到中繼器的XML數據

考慮下面的XML文件 「超簡單xml.xml」(格式化,以節省一些空間),

<items> 
    <item> <one id="ms">Microsoft</one> <two>MSFT</two> </item> 
    <item> <one id="in">Intel</one>  <two>INTC</two> </item> 
    <item> <one id="de">Dell</one>  <two>DELL</two> </item> 
</items> 

一箇中繼器,看起來像這樣,

<asp:Repeater id="SuperSimple" runat="server" OnItemCommand="SuperSimple_ItemDataBound"> 
    <HeaderTemplate> 
     <table border="1"><tr><th>Company</th><th>Symbol</th><th>Wrong</th></tr> 
    </HeaderTemplate> 
    <ItemTemplate> 
     <tr> 
      <td><asp:Label Text=<%#XPath("one") %> runat="server" /></td> 
      <td><asp:CheckBox Text=<%#XPath("two") %> runat="server" id="symbol" /></td> 
     </tr> 
    </ItemTemplate> 
    <FooterTemplate> 
     </table> 
     <asp:Button id="buttonOne" Text="Submit!" runat="server" /> 
    </FooterTemplate> 
</asp:Repeater> 

和以下綁定XML:

private void Page_Load(object sender, EventArgs e) 
{ 
    XmlDataSource xmlSource = new XmlDataSource(); 
    xmlSource.DataFile = "super-simple-xml.xml"; 
    xmlSource.XPath = "items/item"; 

    if (!IsPostBack) // Did this to prevent an error 
    { 
     SuperSimple.DataSource = xmlSource; 
     SuperSimple.DataBind(); 
    } 
} 

我該如何去關於從每個XML ent拉id成爲一個類或變量?

這裏的想法是,我在Repeater中顯示項目。我添加了複選框,因此我可以檢查任何<two>條目,然後按提交。當它回發時,我想將檢查的條目存儲在我製作的課程中。獲取<one><two>非常簡單,因爲它們在Repeater中具有可引用的ID。但XML中的id屬性永遠不會被調用,所以我不知道如何去實現它。當我傳遞數據時,我希望類中的id可以引用。這是可能的,我該怎麼做?

+0

爲了澄清你的問題,你是否想要在你的'Page_Load'C#方法中獲得id屬性的值,或者你是否試圖在標記中取出id值,例如就像你在'一個'和'兩個'? –

+0

在Page_Load內。 – Brendan

+0

但是,最終無論什麼作品。 @Sean解決了後一種情況,似乎可行。我只是假設如果XML文件被頁面訪問,我可以到達它,而不必將其綁定到某個東西。 – Brendan

回答

1

使用XPath @語法得到一個屬性:

<%# XPath("one/@id") %> 

您可以將這個表達式綁定到一個HiddenField和訪問,在回傳:

<asp:HiddenField runat="server" ID="hidID" Value='<%# XPath("one/@id") %>' /> 

添加命令按鈕到<ItemTemplate>

<asp:Button runat="server" ID="btnGetID" Text="Get ID" CommandName="GetID" /> 

在OnItemCommand事件:

protected void SuperSimple_ItemDataBound(object sender, RepeaterCommandEventArgs e) 
{ 
    //check the item type, headers won't contain the control 
    if (e.CommandName == "GetID") 
    { 
     //find the control and put it's value into a variable 
     HiddenField hidID = (HiddenField)e.Item.FindControl("hidID"); 
     string strID = hidID.Value; 
    } 
} 

這是一個另類(我最初發布是因爲我被你的OnItemCommand事件的名稱混淆,以爲你想在數據綁定時間值):

在您的<ItemTemplate>

<asp:Button runat="server" ID="btnGetID" OnClick="btnGetID_Click" Text="Get ID" /> 

代碼隱藏:

protected void btnGetID_Click(object sender, e as EventArgs) 
{ 
    //sender is the button 
    Button btnGetID = (Button)sender; 
    //the button's parent control is the RepeaterItem 
    RepeaterItem theItem = (RepeaterItem)sender.Parent; 
    //find the hidden field in the RepeaterItem 
    HiddenField hidID = (HiddenField)theItem.FindControl("hidID"); 
    //assign to variable 
    string strID = hidID.Value; 
}