在Asp.net中通过Button的CommandArgument传递多个参数

发布于 2024-08-23 19:10:12 字数 375 浏览 10 评论 0原文

我有一个包含多行的 gridview,每行都有一个更新按钮,当有人单击更新按钮时我需要传递 2 个值。 除了将参数打包在 CommandArgument 中并用逗号分隔(过时且不优雅)之外,我如何传递多个参数?

<asp:LinkButton ID="UpdateButton" runat="server" CommandName="UpdateRow" CommandArgument="arg_value" Text="Update and Insert" OnCommand="CommandButton_Click" ></asp:LinkButton>

请注意,无法从页面上的任何控件检索这些值,因此我目前不寻求任何设计解决方案。

I have a gridview with multiple rows, each has a Update button and I need to pass 2 values when someone clicks on Update button.
Aside from packing the arguments inside CommandArgument separated by commas (archaic and not elegant), how would I pass more than one argument?

<asp:LinkButton ID="UpdateButton" runat="server" CommandName="UpdateRow" CommandArgument="arg_value" Text="Update and Insert" OnCommand="CommandButton_Click" ></asp:LinkButton>

As a note, the values can't be retrieved from any controls on the page, so I am presently not seeking any design solutions.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

葬シ愛 2024-08-30 19:10:12

您可以传递分号分隔的值作为命令参数,然后拆分字符串并使用它。

<asp:TemplateField ShowHeader="false">
    <ItemTemplate>
       <asp:LinkButton ID="lnkCustomize" Text="Customize"  CommandName="Customize"  CommandArgument='<%#Eval("IdTemplate") + ";" +Eval("EntityId")%>'  runat="server"> 
       </asp:LinkButton>   
    </ItemTemplate>   
</asp:TemplateField>

在服务器端

protected void gridview_RowCommand(object sender, GridViewCommandEventArgs e)
{
      string[] arg = new string[2];
      arg = e.CommandArgument.ToString().Split(';');
      Session["IdTemplate"] = arg[0];
      Session["IdEntity"] = arg[1];
      Response.Redirect("Samplepage.aspx");
}

You can pass semicolon separated values as command argument and then split the string and use it.

<asp:TemplateField ShowHeader="false">
    <ItemTemplate>
       <asp:LinkButton ID="lnkCustomize" Text="Customize"  CommandName="Customize"  CommandArgument='<%#Eval("IdTemplate") + ";" +Eval("EntityId")%>'  runat="server"> 
       </asp:LinkButton>   
    </ItemTemplate>   
</asp:TemplateField>

at server side

protected void gridview_RowCommand(object sender, GridViewCommandEventArgs e)
{
      string[] arg = new string[2];
      arg = e.CommandArgument.ToString().Split(';');
      Session["IdTemplate"] = arg[0];
      Session["IdEntity"] = arg[1];
      Response.Redirect("Samplepage.aspx");
}
汹涌人海 2024-08-30 19:10:12

@Patrick 的回答是个好主意,值得更多的赞扬!您可以拥有任意数量的数据项,它们都是分开的,并且可以在必要时在客户端使用。

它们也可以以声明方式添加,而不是在代码中添加。我只是对 GridView 这样做了,如下所示:

<asp:TemplateField HeaderText="Remind">
  <ItemTemplate>
    <asp:ImageButton ID="btnEmail"  
        data-rider-name="<%# ((Result)((GridViewRow) Container).DataItem).Rider %>"
        data-rider-email="<%# ((Result)((GridViewRow) Container).DataItem).RiderEmail %>"
        CommandName="Email" runat="server" ImageAlign="AbsMiddle" ImageUrl="~/images/email.gif" />
  </ItemTemplate> 
</asp:TemplateField>

在 RowCommand 中,您执行以下操作:

void gvMyView_RowCommand(object sender, GridViewCommandEventArgs e)
{
    if (e.CommandName == "Email")
    {
        var btnSender = (ImageButton)e.CommandSource;
        var riderName = btnSender.Attributes["data-rider-name"];
        var riderEmail = btnSender.Attributes["data-rider-email"];
        // Do something here
    }
}

比将所有值与分隔符放在一起并在最后再次解压要干净得多。

不要忘记测试/清理从页面返回的任何数据,以防它被篡改!

@Patrick's answer is a good idea, and deserves more credit!. You can have as many data items as you want, they are all separated, and can be used client side if necessary.

They can also be added declaratively rather than in code. I just did this for a GridView like this:

<asp:TemplateField HeaderText="Remind">
  <ItemTemplate>
    <asp:ImageButton ID="btnEmail"  
        data-rider-name="<%# ((Result)((GridViewRow) Container).DataItem).Rider %>"
        data-rider-email="<%# ((Result)((GridViewRow) Container).DataItem).RiderEmail %>"
        CommandName="Email" runat="server" ImageAlign="AbsMiddle" ImageUrl="~/images/email.gif" />
  </ItemTemplate> 
</asp:TemplateField>

In the RowCommand, you do this:

void gvMyView_RowCommand(object sender, GridViewCommandEventArgs e)
{
    if (e.CommandName == "Email")
    {
        var btnSender = (ImageButton)e.CommandSource;
        var riderName = btnSender.Attributes["data-rider-name"];
        var riderEmail = btnSender.Attributes["data-rider-email"];
        // Do something here
    }
}

So much cleaner than hacking all the values together with delimiters and unpacking again at the end.

Don't forget to test/clean any data you get back from the page, in case it's been tampered with!

天赋异禀 2024-08-30 19:10:12

经过一番探索后,凯尔西似乎是正确的。

当你想使用它时,只需使用逗号或其他东西并将其分开即可。

After poking around it looks like Kelsey is correct.

Just use a comma or something and split it when you want to consume it.

老子叫无熙 2024-08-30 19:10:12

我的方法是使用属性集合从代码隐藏添加 HTML 数据属性。这与 jquery 和客户端脚本更加一致。

// This would likely be done with findControl in your grid OnItemCreated handler
LinkButton targetBtn = new LinkButton();


// Add attributes
targetBtn.Attributes.Add("data-{your data name here}", value.ToString() );
targetBtn.Attributes.Add("data-{your data name 2 here}", value2.ToString() );

然后通过属性集合检索值

string val = targetBtn.Attributes["data-{your data name here}"].ToString();

My approach is using the attributes collection to add HTML data- attributes from code behind. This is more inline with jquery and client side scripting.

// This would likely be done with findControl in your grid OnItemCreated handler
LinkButton targetBtn = new LinkButton();


// Add attributes
targetBtn.Attributes.Add("data-{your data name here}", value.ToString() );
targetBtn.Attributes.Add("data-{your data name 2 here}", value2.ToString() );

Then retrieve the values through the attribute collection

string val = targetBtn.Attributes["data-{your data name here}"].ToString();
涙—继续流 2024-08-30 19:10:12

在上面的评论中添加一个更优雅的方法,

<asp:GridView ID="grdParent" runat="server" BackColor="White" BorderColor="#DEDFDE"
                           AutoGenerateColumns="false"
                            OnRowDeleting="deleteRow"
                         GridLines="Vertical">
      <asp:BoundField DataField="IdTemplate" HeaderText="IdTemplate" />
      <asp:BoundField DataField="EntityId" HeaderText="EntityId"  />
    <asp:TemplateField ShowHeader="false">
        <ItemTemplate>
           <asp:LinkButton ID="lnkCustomize" Text="Delete"  CommandName="Delete"  CommandArgument='<%#Eval("IdTemplate") + ";" +Eval("EntityId")%>'  runat="server"> 
           </asp:LinkButton>   
        </ItemTemplate>   
    </asp:TemplateField>
     </asp:GridView>

在服务器端:

protected void deleteRow(object sender, GridViewDeleteEventArgs e)
{
    string IdTemplate= e.Values["IdTemplate"].ToString();
    string EntityId = e.Values["EntityId"].ToString();

   // Do stuff..
}

A little more elegant way of doing the same adding on to the above comment ..

<asp:GridView ID="grdParent" runat="server" BackColor="White" BorderColor="#DEDFDE"
                           AutoGenerateColumns="false"
                            OnRowDeleting="deleteRow"
                         GridLines="Vertical">
      <asp:BoundField DataField="IdTemplate" HeaderText="IdTemplate" />
      <asp:BoundField DataField="EntityId" HeaderText="EntityId"  />
    <asp:TemplateField ShowHeader="false">
        <ItemTemplate>
           <asp:LinkButton ID="lnkCustomize" Text="Delete"  CommandName="Delete"  CommandArgument='<%#Eval("IdTemplate") + ";" +Eval("EntityId")%>'  runat="server"> 
           </asp:LinkButton>   
        </ItemTemplate>   
    </asp:TemplateField>
     </asp:GridView>

And on the server side:

protected void deleteRow(object sender, GridViewDeleteEventArgs e)
{
    string IdTemplate= e.Values["IdTemplate"].ToString();
    string EntityId = e.Values["EntityId"].ToString();

   // Do stuff..
}
柒夜笙歌凉 2024-08-30 19:10:12

将其存储在 gridview datakeys 集合中,或者将其存储在同一单元格内的隐藏字段中,或者将这些值连接在一起。这是唯一的办法。您不能在一个链接中存储两个值。

Either store it in the gridview datakeys collection, or store it in a hidden field inside the same cell, or join the values together. That is the only way. You can't store two values in one link.

北渚 2024-08-30 19:10:12

如果你想传递两个值,你可以使用这种方法

<asp:LinkButton ID="RemoveFroRole" Text="Remove From Role" runat="server"
CommandName='<%# Eval("UserName") %>' CommandArgument='<%# Eval("RoleName") %>'
 OnClick="RemoveFromRole_Click" />

基本上我将 {CommmandName,CommandArgument} 视为键值。从数据库字段设置两者。在这种情况下,您必须使用 OnClick 事件并使用 OnCommand 事件,我认为这是更干净的代码。

If you want to pass two values, you can use this approach

<asp:LinkButton ID="RemoveFroRole" Text="Remove From Role" runat="server"
CommandName='<%# Eval("UserName") %>' CommandArgument='<%# Eval("RoleName") %>'
 OnClick="RemoveFromRole_Click" />

Basically I am treating {CommmandName,CommandArgument} as key value. Set both from database field. You will have to use OnClick event and use OnCommand event in this case, which I think is more clean code.

渔村楼浪 2024-08-30 19:10:12

您可以使用分隔符分割参数(分隔符不得位于参数值内 - 例如“|”)。
参数名称必须是数据源的有效名称。
单引号用于命令参数,双引号用于参数名称。

<%-- BUTTON VIEWCMD --%>
<asp:TemplateField HeaderText="" SortExpression="" ItemStyle-CssClass="widthP07 textAlignCenter">
    <ItemTemplate>
        <asp:Button ID="ButtonVIEWCMD" runat="server" Text="View Detail"
         CommandName="VIEWCMD" 
         CommandArgument='<%# Eval("param1") + "|" + Eval("param2") + "|" + Eval("param3") %>' />
                        
    </ItemTemplate>
</asp:TemplateField>

服务器代码

/// <summary>
/// SET - Process GridView Row Commands
/// </summary>
protected void GridView_RowCommand(object sender, GridViewCommandEventArgs e)
{
    // INIT 
    string tempArguments = string.Empty;

    try
    {
        // CTRL - gridview row click
        switch (e.CommandName)
        {
            case "VIEWCMD":
                // GET 
                tempArguments = (string)(e.CommandArgument);
                // GET 
                string[] tempParam = tempArguments.Split('|');

                // GET 
                // tempParam[0];
                // tempParam[1];
                // tempParam[2];
                
                // .........

                break;

            default:
                break;
        }
    }
    catch (Exception ex)
    {
        // ERR .......
    }
}

You can split the parameters using a separator (that must not be inside the parameter values - ex. "|").
Names of parameters must be valid names of the data source.
Single quotes for the command arguments, and double quotes for the names of the parameters.

<%-- BUTTON VIEWCMD --%>
<asp:TemplateField HeaderText="" SortExpression="" ItemStyle-CssClass="widthP07 textAlignCenter">
    <ItemTemplate>
        <asp:Button ID="ButtonVIEWCMD" runat="server" Text="View Detail"
         CommandName="VIEWCMD" 
         CommandArgument='<%# Eval("param1") + "|" + Eval("param2") + "|" + Eval("param3") %>' />
                        
    </ItemTemplate>
</asp:TemplateField>

server code

/// <summary>
/// SET - Process GridView Row Commands
/// </summary>
protected void GridView_RowCommand(object sender, GridViewCommandEventArgs e)
{
    // INIT 
    string tempArguments = string.Empty;

    try
    {
        // CTRL - gridview row click
        switch (e.CommandName)
        {
            case "VIEWCMD":
                // GET 
                tempArguments = (string)(e.CommandArgument);
                // GET 
                string[] tempParam = tempArguments.Split('|');

                // GET 
                // tempParam[0];
                // tempParam[1];
                // tempParam[2];
                
                // .........

                break;

            default:
                break;
        }
    }
    catch (Exception ex)
    {
        // ERR .......
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文