1. in ASP. net ajax, how does one use JavaScript to call server methods?
This does not mean calling a simple PageMethod. Because the static method cannot operate the control of the current page, the static PageMethod function is the same as that of a common WebService and is quite limited.
Therefore, calling a common server method is actually initiating an asynchronous callback. The simplest implementation method is through UpdatePanel.
First, define a hidden LinkButton to call the operation we want to perform in its event processing:
<Asp: LinkButton ID = "linkUpdatePosts" runat = "server" style = "display: 'none';" OnClick = "linkUpdatePosts_Clicked"/>
// Refresh the post list (called by the client js)
Protected void linkUpdatePosts_Clicked (object sender, EventArgs e)
{
LoadPosts ();
}
Then, you can define a function in JavaScript to trigger the callback of this LinkButton:
// Refresh the post list
Function refreshPosts (){
_ DoPostBack ('<% = linkUpdatePosts. UniqueID %> ','');
}
// Refresh the post list
Function refreshPosts (){
_ DoPostBack ('<% = linkUpdatePosts. ClientID %>'. split ('_'). join ('$ '),'');
} Here, pay attention to split ('_'). the use of join ('$') is because the control identifier used as the _ doPostBack parameter is separated by $, and ClientID is separated by _, which must be converted between the two.
2. How to get the value in the cell in the editing state of the GridView?
Are you still using this code?
Var txtName = grid1.Rows [e. RowIndex]. Cells [0]. FindControl ("txtName") as TextBox;
If (txtName! = Null)
{
// Read value
//
}
In fact, these operations (search for controls in cells and try to get the values) have been encapsulated. Now, you only need to call the ExtractValuesFromCell method.
This method is also supported by many column types:
DataControlField, BoundField, AutoGeneratedField, CheckBoxField, ImageField, TemplateField, DynamicField
You can use it in the RowUpdating, RowDeleting, and other events of the GridView. This method can be used to extract values to the required dictionary and then read from the dictionary. These dictionaries include e. Keys, e. NewValues, and e. OldValues.
Example code:
// Update
Protected void grid1_RowUpdating (object sender, GridViewUpdateEventArgs e)
{
Var row = grid1.Rows [e. RowIndex];
// Extract the value of the Id field
Grid1.Columns [0]. ExtractValuesFromCell (
E. Keys,
Row. Cells [0] as DataControlFieldCell,
DataControlRowState. Edit,
True/* include readonly */);
// Extract the value of the Name field
Grid1.Columns [1]. ExtractValuesFromCell (
E. NewValues,
Row. Cells [1] as DataControlFieldCell,
DataControlRowState. Edit,
True/* include readonly */);
Var id = int. Parse (e. Keys ["id"]. ToString ());
Var name = (string) e. NewValues ["name"];
// Perform related database update operations
//
}
In this way, we can use BoundField as much as possible in most cases, and can correctly read the value during editing, saving a bunch of custom TemplateField code.