问题
I have a GridView control on my page that I have defined a number of BoundFields for. Each row of the databound GridView has a CommandField (Select), for which I want to send the PostBack to a new page.
Of course I could easily send the NewSelectedIndex in a QueryString, but I'd rather keep that information hidden from the user. Suggestions?
回答1:
Leppie is right. The GridView has no PostbackUrl property. However, you can do what you want by using a standard control, which has a PostbackUrl property.
<asp:TemplateField AccessibleHeaderText="Edit">
<ItemTemplate>
<asp:Button runat="server" ID="btnEdit" PostBackUrl="~/Default.aspx" OnClientClick='form1.ActivityId.value = this.Tag;' Tag='<%# Eval("ActivityId") %>' Text="Edit"/>
</ItemTemplate>
</asp:TemplateField>
In this sample code, I added a TemplateColumn to the GridView. I use a dynamically added Tag attribute for the button to pass the Id, then I use Javascript code to put the value in a hidden field, and then the button simply postsback to the page specified in the PostbackUrl property.
回答2:
Use a HyperLinkField column in your GridView:
<asp:HyperLinkField AccessibleHeaderText="Edit" DataNavigateUrlFields="ActivityId" DataNavigateUrlFormatString="AcitivtyEdit.aspx?id={0}" Text="Edit Activity" />
Of course, as you said, this option shows the id in the url. To hide it (although anyone can check out your javascript and see what you do) you have two options: 1. Use Javascript code to set a hidden field with the id, change the Form postback (action) address and then submit the form. You have to allow your asp.net site to allow postback from a different page 2. Allow the Command to postback to the same page that hosts the GridView and in the server side event handler to a Server.Transfer to your page (this option presents otehr issues on sequential postbacks...)
回答3:
Thanks Sergiu Damian.
I use MasterPages and the UniqueID os hidden field may vary. I need post two values.
In the event Gridview_RowDataBound i put this code:
If e.Row.RowType = DataControlRowType.DataRow Then
e.Row.Cells(12).Text = ""
Dim img As New WebControls.ImageButton
img.PostBackUrl = "NecesidadesPostBack.aspx"
img.ImageUrl = "imagenes/edit.png"
img.OnClientClick = HDLB.UniqueID.ToString & ".value = '" & e.Row.Cells(0).Text & "'; " & HDPT.UniqueID.ToString & ".value = '" & e.Row.Cells(1).Text & "';"
img.AlternateText = "Edit"
e.Row.Cells(12).Controls.Add(img)
End If
I have 2 hidden fields (HDLB and HDPT). The event OnClientClick modify the value of this hidden fields with the value of the first and second cell onto the grid.
来源:https://stackoverflow.com/questions/333484/can-the-postbackurl-be-set-for-a-gridview-commandfield