0

I have two asp:Labels, the first of which is replaced with a few buttons and the second with a list of items.

I want to click on the buttons to filter the items.

The contents of the buttons are added programmatically by replacing the text with html and works fine.

asp:

<form id="form1" runat="server">
  <asp:Label id="filters" runat="server" Text="Filters here"/>
  <asp:Label id="itemList" runat="server" Text="List of items here"/>
</form>

resultant html of filters label:

<input type="submit" onclientclick="Load_Items(0)" runat="server" value="First"/>
<input type="submit" onclientclick="Load_Items(1)" runat="server" value="Second"/>
<input type="submit" onclientclick="Load_Items(2)" runat="server" value="Third"/>

relevant c#:

protected void Page_Load(object sender, EventArgs e)
{
  if (!IsPostBack)
  {
    Load_Items(0);
  }
}
public void Load_Items(int filterType)
{
  //code to load items (pseudo below)
  for each row in list
    if filterType = itemType
      build string
  replace second label with string
}

On page load everything happens just as I want it to with the contents being filtered by the first item (hence Load_Items(0)), and if I manually change the 0 to another number in Page_Load, it filters by the other types, but if I click the buttons which are programmatically added, nothing happens other than what looks like the page refreshing.

I know the post back check is working by adding a text replacement before and inside it.

I've also added an asp:button to make sure it's not something to do with the way the buttons are added as below (with some extra things recommended from searches):

<asp:Button runat="server" CausesValidation="False" onclientclick="Load_Items(2); return false;" text="Submit" />

So what could be the issue?

4

2 に答える 2

2

このOnClientClickプロパティは、ボタンがクリックされたときにブラウザで実行する JavaScript を指定します。という名前の JavaScript 関数がない可能性があるLoad_Itemsため、スクリプト エラーが発生し、ボタンによってフォームがポストバックされます。

サーバー側Clickイベントはサーバー上で発生しますが、パラメーターを渡すことはできません。ボタン インスタンスと空のEventArgsインスタンスのみを取得します。

プロパティと組み合わせてCommandイベントを使用する方がよい場合があります。CommandArgument

<asp:Button runat="server" CommandArgument="2" OnCommand="Load_Items" ...

イベント ハンドラーは、 のCommandArgumentプロパティを使用CommandEventArgsして、クリックされたボタンから引数にアクセスします。

protected void Load_Items(object sender, CommandEventArgs e)
{
    Load_Items(Convert.ToInt32(e.CommandArgument));
}
于 2013-07-26T14:51:03.927 に答える