How to use __doPostBack() function in asp.net - asp.net

I am trying to trigger button event from the JS code. But doPostBack in JS function reg() is not directing to the c# code. Please tell me what's wrong. Here is my code:
<script>
function reg() {
var name = document.getElementById('name').value;
var id = document.getElementById('cnic').value;
var age = document.getElementById('age').value;
var ph = document.getElementById('phone').value;
var pas = document.getElementById('pass').value;
if (id == '' || pas == '' || age == '' || ph == '' || pas == '')
window.alert("Write all fields");
else {
__doPostBack('<%= Button1.UniqueID%>','')
}
}
</script>
<div >
<asp:Button id="Button1" OnClientClick="reg()" runat="server" Text="Submit"/>
</div>
Here is the server side c# function associated with the button:
protected void Btn_Click(object sender, EventArgs e)
{
Button clickedButton = (Button)sender;
clickedButton.Text = "...button clicked...";
}
Note: In else block, I want reg() function to redirect to the Btn_Click function.

Related

ASP.NET GridView RowDataBound TemplateField FindControl is null after invalid data entered

I am having trouble with my GridView RowDataBound event after I click on Save to save the data to the database.
I have a grid with 5 columns: Tag Name, Current Timestamp, Current Value, New Date, New Value.
The idea is the user will enter into the New Date/New Value to update the data in the database. The Current Timestamp and Current Value are what is already stored in the database.
I use a JQuery editor to enter the date.
When I click on Save, I have server side validation in place to check the entered values. If the data is valid, a message under the text in the New Value column is displayed to indicate this. If the validation fails, then a message in the New Value column is displayed.
New Date and New Value columns are TemplateField's. The New Value TemplateField contains a panel with two labels - one for OK status and the other for error.
The error occurs in MyDataGrid_RowDataBound when I call any e.Row.FindControl(...) which is triggered from the Save button click when I rebind.
It works ok if a valid value has been entered but if an invalid value is entered then it errors. In order to simplify the scenario, enter 100 for a valid value and anything else for an invalid.
This WebForm has been the trouble of my life. Maybe I shouldn't have used a GridView.
Anyway, I would appreciate any help here to identify the issue. And maybe a better approach to the form code.
I've took the code from my solution and moved it into a standalone solution to reproduce the issue. I've removed the database access and populated a datastructure. This is only ever done (once) in the Page Load when the page is initially loaded.
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<link rel="stylesheet" href="Styles/jquery-ui-timepicker-addon.css" />
<link rel="stylesheet" href="Styles/jquery-ui-1.10.1.custom.css" />
<link rel="stylesheet" href="Styles/jquery-ui-1.10.1.custom.min.css" />
<script src="Scripts/jquery-1.9.1.js"></script>
<script src="Scripts/jquery-ui-1.10.1.custom.js"></script>
<script src="Scripts/jquery-ui-1.10.1.custom.min.js"></script>
<script src="Scripts/jquery-ui-timepicker-addon.js"></script>
</head>
<body>
<script type="text/javascript">
/** Disable backkey */
$(document).unbind('keydown').bind('keydown', function (event) {
var doPrevent = false;
if (event.keyCode === 8) {
var d = event.srcElement || event.target;
if ((d.tagName.toUpperCase() === 'INPUT' && (d.type.toUpperCase() === 'TEXT' || d.type.toUpperCase() === 'PASSWORD' || d.type.toUpperCase() === 'FILE'))
|| d.tagName.toUpperCase() === 'TEXTAREA') {
doPrevent = d.readOnly || d.disabled;
} else {
doPrevent = true;
}
}
if (doPrevent) {
event.preventDefault();
}
});
$(function () {
$(".datetimepicker").datetimepicker({
changeMonth: true,
changeYear: true
});
});
$(function () {
$(".datepicker").datepicker({
changeMonth: true,
changeYear: true
});
});
$(function () {
$(".timepicker").timepicker({ showTimezone: false });
});
</script>
<form id="form1" runat="server">
<div>
<asp:GridView ID="MyDataGrid" runat="server"
EnableModelValidation="True"
DataKeyNames="Id"
AutoGenerateColumns="False"
AutoGenerateSelectButton="False"
EmptyDataText="There is no plant data configured."
OnRowDataBound="MyDataGrid_RowDataBound">
<Columns>
<asp:BoundField DataField="Name" SortExpression="Name" HeaderText="Tag Name"></asp:BoundField>
<asp:BoundField DataField="Date" SortExpression="Date" HeaderText="Current Timestamp"></asp:BoundField>
<asp:BoundField DataField="Value" SortExpression="Value" HeaderText="Current Value"></asp:BoundField>
<asp:TemplateField HeaderText="New Date<BR/>MM/DD/YYYY HH:MM">
<ItemTemplate>
<asp:TextBox ID="txtNewDate" runat="server" CssClass="datetimepicker"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="New Value">
<ItemTemplate>
<asp:TextBox ID="txtNewValue" runat="server"></asp:TextBox>
<asp:Panel ID="ErrorPanel" runat="server">
<br />
<asp:Label ID="lblError" runat="server" ForeColor="Red"></asp:Label>
<asp:Label ID="lblStatus" runat="server" ForeColor="#66cc00"></asp:Label>
</asp:Panel>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:Button ID="SaveButton" runat="server"
Text="Save Values"
ToolTip="Save the current changes."
OnClick="SaveButton_Click" />
</div>
</form>
</body>
</html>
Code Behind
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.UI.WebControls;
public partial class _Default : System.Web.UI.Page
{
private const int COL_NEW_DATE = 3;
private const int COL_NEW_VALUE = 4;
bool canEdit = true;
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
PopulateDataGrid();
}
}
private void PopulateDataGrid()
{
// this is where i load from the database
List<RowData> data = new List<RowData>() {
new RowData() { Date = new DateTime(2000,1,1), Editable = true, Name = "Data Item 1", Value = 100.0 },
new RowData() { Date = new DateTime(2000,1,1), Editable = false, Name = "Data Item 2", Value = 120.0 },
new RowData() { Date = new DateTime(2000,1,1), Editable = true, Name = "Data Item 3", Value = 19.0 }
};
this.MyDataGrid.DataSource = data;
this.MyDataGrid.DataBind();
ViewState["GridData"] = this.MyDataGrid.DataSource;
}
private void SaveData()
{
for (int i = Page.Validators.Count - 1; i >= 0; i--)
Page.Validators.Remove(Page.Validators[i]);
ValidateData();
List<RowData> rowDataList = (List<RowData>)ViewState["GridData"];
if (this.IsValid)
{
foreach (GridViewRow row in this.MyDataGrid.Rows)
{
if (row.RowType == System.Web.UI.WebControls.DataControlRowType.DataRow && row.Enabled)
{
RowData dataItem = rowDataList[row.DataItemIndex];
var txtNewValue = row.Cells[COL_NEW_VALUE].FindControl("txtNewValue") as TextBox;
var txtNewDate = row.Cells[COL_NEW_DATE].FindControl("txtNewDate") as TextBox;
if (dataItem != null && txtNewDate != null && txtNewValue != null && !string.IsNullOrEmpty(txtNewValue.Text) && !string.IsNullOrEmpty(txtNewDate.Text))
{
var newValue = double.Parse(txtNewValue.Text);
var newDate = DateTime.Parse(txtNewDate.Text);
dataItem.InfoText = "Value written successfully for " + txtNewDate.Text;
dataItem.ErrorText = string.Empty;
dataItem.EnteredDateCache = string.Empty;
dataItem.EnteredValueCache = string.Empty;
if ((dataItem.Date.HasValue && DateTime.Compare(newDate, dataItem.Date.Value) >= 0) || !dataItem.Date.HasValue)
{
dataItem.Date = newDate;
dataItem.Value = newValue;
}
}
}
}
// save any outstanding changes if valid removed from demo
}
ViewState["GridData"] = rowDataList;
}
private void ValidateData()
{
List<RowData> rowDataList = (List<RowData>)ViewState["GridData"];
foreach (GridViewRow row in this.MyDataGrid.Rows)
{
if (row.RowType == System.Web.UI.WebControls.DataControlRowType.DataRow && row.Enabled)
ValidateDataRow(rowDataList, row);
}
}
private void ValidateDataRow(List<RowData> rowDataList, GridViewRow gridViewRow)
{
RowData rowData = rowDataList[gridViewRow.DataItemIndex];
bool valueOK = false;
var txtNewValue = gridViewRow.Cells[COL_NEW_VALUE].FindControl("txtNewValue") as TextBox;
var txtNewDate = gridViewRow.Cells[COL_NEW_DATE].FindControl("txtNewDate") as TextBox;
var labelError = gridViewRow.Cells[COL_NEW_VALUE].FindControl("lblError") as Label;
var labelInfo = gridViewRow.Cells[COL_NEW_VALUE].FindControl("lblStatus") as Label;
labelInfo.Text = string.Empty;
labelError.Text = string.Empty;
rowData.InfoText = string.Empty;
rowData.ErrorText = string.Empty;
rowData.EnteredDateCache = txtNewDate.Text;
rowData.EnteredValueCache = txtNewValue.Text;
if (rowData != null && (!string.IsNullOrEmpty(txtNewValue.Text) || !string.IsNullOrEmpty(txtNewDate.Text)))
{
if (!txtNewValue.Text.IsNumber())
{
rowData.ErrorText = rowData.Name + " must be a number.";
AddCustomValidatorForCell(rowData.ErrorText, gridViewRow, 4);
}
else
{
if (txtNewValue.Text != "100")
{
rowData.ErrorText = rowData.Name + " is invalid.";
AddCustomValidatorForCell(rowData.ErrorText, gridViewRow, 4);
}
else
{
valueOK = true;
}
}
}
}
private void AddCustomValidatorForCell(string errorMessage, GridViewRow gridViewRow, int cellIndex)
{
var labelError = gridViewRow.Cells[cellIndex].FindControl("lblError") as Label;
var divInfoError = gridViewRow.Cells[cellIndex].FindControl("ErrorPanel") as Panel;
labelError.Text = errorMessage;
labelError.ToolTip = errorMessage;
labelError.Attributes.Add("style", "color: red;");
CustomValidator validatePower = new CustomValidator()
{
IsValid = false,
ErrorMessage = errorMessage,
EnableViewState = false,
};
Page.Validators.Add(validatePower);
}
protected void SaveButton_Click(object sender, EventArgs e)
{
SaveData();
this.MyDataGrid.DataSource = ViewState["GridData"];
this.MyDataGrid.DataBind();
}
protected void MyDataGrid_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == System.Web.UI.WebControls.DataControlRowType.DataRow)
{
var rowData = e.Row.DataItem as RowData;
if (rowData != null)
{
DataControlFieldCell txtNewDate = (DataControlFieldCell)e.Row.Cells[COL_NEW_DATE];
DataControlFieldCell txtNewValue = (DataControlFieldCell)e.Row.Cells[COL_NEW_VALUE];
e.Row.Cells[1].Text = rowData.Date.HasValue ? rowData.Date.ToString() : string.Empty;
e.Row.Cells[2].Text = rowData.Value.HasValue ? rowData.Value.Value.ToString() : string.Empty;
txtNewValue.Enabled = txtNewDate.Enabled = (canEdit & rowData.Editable);
if (!string.IsNullOrEmpty(rowData.EnteredDateCache))
txtNewDate.Text = rowData.EnteredDateCache;
if (!string.IsNullOrEmpty(rowData.EnteredValueCache))
txtNewValue.Text = rowData.EnteredValueCache;
(e.Row.FindControl("lblStatus") as Label).Text = rowData.InfoText;
(e.Row.FindControl("lblError") as Label).Text = rowData.ErrorText;
//(e.Row.FindControl("ErrorPanel") as Panel).Visible = (!string.IsNullOrEmpty(rowData.InfoText) || !string.IsNullOrEmpty(rowData.ErrorText));
}
}
}
[Serializable()]
private class RowData
{
public int Id { get; set; }
public string Name { get; set; }
public DateTime? Date { get; set; }
public double? Value { get; set; }
public string ValidationRule { get; set; }
public string ErrorText { get; set; }
public string InfoText { get; set; }
public string EnteredDateCache { get; set; }
public string EnteredValueCache { get; set; }
public bool Editable { get; set; }
}
}
public static class StringExtensionMethods
{
public static bool IsNumber(this String str)
{
double Number;
if (double.TryParse(str, out Number)) return true;
return false;
}
}
Looks like I was incorrectly setting the controls incorrectly in the RowDataBound event. This should be:
if (e.Row.RowType == System.Web.UI.WebControls.DataControlRowType.DataRow)
{
var rowData = e.Row.DataItem as RowData;
if (rowData != null)
{
DataControlFieldCell txtNewDate = (DataControlFieldCell)e.Row.Cells[COL_NEW_DATE];
if (!string.IsNullOrEmpty(rowData.EnteredValueCache))
{
var txtNewValue = (e.Row.FindControl("txtNewValue") as TextBox);
txtNewValue.Enabled = txtNewDate.Enabled = (canEdit & rowData.Editable);
txtNewValue.Text = rowData.EnteredValueCache;
}
(e.Row.FindControl("lblStatus") as Label).Text = rowData.InfoText;
(e.Row.FindControl("lblError") as Label).Text = rowData.ErrorText;
}
}
Remove the following lines from SaveData:
(row.FindControl("lblStatus") as Label).Text = dataItem.InfoText;
(row.FindControl("lblError") as Label).Text = dataItem.ErrorText;
Remove the following from ValidateDataRow:
labelInfo.Text = string.Empty;
labelError.Text = string.Empty;
I am assuming that calling the following:
DataControlFieldCell txtNewValue = (DataControlFieldCell)e.Row.Cells[COL_NEW_VALUE];
if (!string.IsNullOrEmpty(rowData.EnteredValueCache))
txtNewValue.Text = rowData.EnteredValueCache;
Will remove the controls from the template column when the data is set (which would be on the invalid value as it is not cleared in the cache) which is why I saw the error when an invalid value was entered.

n ASP .NET 4.5 SelectMethod is not able to bind data to grid view on button click

I am using ASP.Net 4.5 , and facing an issue regarding with data binding for grid view using 'Select method'.
The grid is able to bind the data on custom paging too.
The issue lies in filtering the data. I have a asp button, By clicking on this i am able to get filtered data using stored proc. but this time grid is not able to call the method which i mentioned in aspx page for that grid in SelectMethod.
<asp:GridView ID="gEmployee" runat="server"
AutoGenerateColumns="False"
OnRowCommand="gEmployee_Command" CellPadding="4"
OnRowDataBound="gEmployee_RowDataBound"
AllowCustomPaging="true" PageSize="10" PagerSettings-Visible="false"
CssClass="mGrid"
AllowSorting ="true"
AlternatingRowStyle-CssClass="alt"
ItemType="ModelEntityLayer.ClsEmployee" SelectMethod="BindGrid"
OnSorting ="gEmployee_OnSorting" HeaderStyle-Wrap="false" DataKeyNames="PropClockNumber" >
code above shows the properties which i have set for grid view.
public IQueryable<ClsEmployee> BindGrid()
{
int intTotalPages = 0;
objBALEmployee = new ClsEmployeeBAL();
List<ClsEmployee> employee = null;
if ((string)Session["QueryResult"] != null)
{
employee = objBALEmployee.GetPageWiseData(gEmployee.PageIndex, gEmployee.PageSize, ViewState["SortExpression"] != null ? ViewState["SortExpression"].ToString() : ViewState["ClockNumber"].ToString(), ViewState["SortOrder"] != null ? ViewState["SortOrder"].ToString() : "asc", ref intTotalPages, ((string)Session["QueryResult"]));
Session.Remove("QueryResult");
}
else
{
if (Convert.ToInt32(ViewState["IsEditSearch"]) != 1)
{
employee = objBALEmployee.GetPageWiseData(gEmployee.PageIndex, ViewState["SortExpression"] != null ? ViewState["SortExpression"].ToString() : ViewState["ClockNumber"].ToString(), ViewState["SortOrder"] != null ? ViewState["SortOrder"].ToString() : "asc", gEmployee.PageSize, ref intTotalPages);
}
else
{
employee = objBALEmployee.GetPageWiseData(gEmployee.PageIndex, gEmployee.PageSize, ViewState["SortExpression"] != null ? ViewState["SortExpression"].ToString() : ViewState["ClockNumber"].ToString(), ViewState["SortOrder"] != null ? ViewState["SortOrder"].ToString() : "asc", ref intTotalPages, dlEmployee.SelectedValue+" = '"+txtSearch.Text.Trim()+"'");
}
}
var lstEmployee = employee.AsQueryable();
if (intTotalPages > 0)
{
CustomPager.TotalPages = intTotalPages %gEmployee.PageSize == 0 ? intTotalPages /gEmployee.PageSize : intTotalPages / gEmployee.PageSize + 1;
CustomPager.Visible = true;
lblNoRecordsFound.Visible = false;
NoRecords.Visible = false;
}
else
{
CustomPager.Visible = false;
lblNoRecordsFound.Visible = true;
NoRecords.Visible = true;
}
ExportData1.DisableBtn(gEmployee);
ExportData.ExportCheck = false;
return lstEmployee;
}
The above code shows the bindGrid method which i have set for the selectMethod in grid.
protected void btnGo_Click(object sender, EventArgs e)
{
ViewState["IsEditSearch"] = "1";
hiddenSearchField.Value = dlEmployee.SelectedValue;
hiddenSearchValue.Value = txtSearch.Text.Trim();
gEmployee.SelectMethod = "BindGrid";
}
The above code is written for button click.
Though i have written gEmployee.SelectMethod = "BindGrid"; once again on click code, BindGrid is not getting fired. So i am not able to bind my newly filtered data to grid.
Please guide me on this.
Thanks.
I think you'll need to add a line at the end of btnGo_Click that explictly calls DataBind() on the grid:
protected void btnGo_Click(object sender, EventArgs e)
{
ViewState["IsEditSearch"] = "1";
hiddenSearchField.Value = dlEmployee.SelectedValue;
hiddenSearchValue.Value = txtSearch.Text.Trim();
gEmployee.SelectMethod = "BindGrid";
gEmployee.DataBind();
}

check/uncheckbox in gridview tracking

i have a below gridview control with a checkbox on it, so my question is when i hit on save button i able to find the checkbox which have been checked and till here no problem, but the problem started when the user tries to uncheck the checkedbox so how would i track the changes and save it into the db that has been checked. anyhelp?
List<Employee> result = new List<Employee>();
long Id = (long)Session["Id"];
result = Employee.GetEmployeeById(Id);
foreach (GridViewRow row in gv.Rows)
{
CheckBox chkBox = row.FindControl("chkSelected") as CheckBox;
if (c != null)
{
if (result.Count > 0)
{
foreach (Employee item in result)
{
Label Id = row.FindControl("lblId") as Label;
if (Id.Text == item.Id.ToString())
{
chkBox.Checked = true;
}
else
{
chkBox.Checked = false;
}
}
}
<asp:TemplateField HeaderText="Select">
<ItemTemplate>
<asp:CheckBox ID="chkSelected" runat="server" Checked="false"></asp:CheckBox>
</ItemTemplate>
</asp:TemplateField>
<script language="javascript" type="text/javascript">
function SelectAll(cb)
{
var gvVar = document.getElementById("<%= gv.ClientID %>");
var cell;
if (gvVar.rows.length > 0)
{
for (i=1; i<gvVar.rows.length; i++)
{
cell = gvVar.rows[i].cells[0];
for (j=0; j<cell.childNodes.length; j++)
{
if (cell.childNodes[j].type =="checkbox")
{
cell.childNodes[j].checked = document.getElementById(cb).checked;
}
}
}
}
}
//--------------------------------------------------------------------------------------------.
function Select(cb)
{
var total = parseInt('<%= this.gv.Rows.Count %>');
var counter=0;
var cbSelectAll=document.getElementById(cb);
var gvVar = document.getElementById("<%= gv.ClientID %>");
var cell;
if (gvVar.rows.length > 0)
{
for (i=1; i<gvVar.rows.length; i++)
{
cell = gvVar.rows[i].cells[0];
for (j=0; j<cell.childNodes.length; j++)
{
if (cell.childNodes[j].type =="checkbox")
{
if(cell.childNodes[j].checked)
counter++;
else
counter--;
}
}
}
}
if(counter==total)
cbSelectAll.checked=true;
else if(counter<total)
cbSelectAll.checked=false;
}
</script>
//----------------------------------------------------------------------------------------
protected void gv_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow && (e.Row.RowState == DataControlRowState.Normal || e.Row.RowState == DataControlRowState.Alternate))
{
CheckBox cbSelect = (CheckBox)e.Row.Cells[0].FindControl("cbSelect");
CheckBox cbSelectAll = (CheckBox)this.gv.HeaderRow.FindControl("cbSelectAll");
cbSelect.Attributes.Add("onclick", "javascript:Select('" + cbSelectAll.ClientID + "')");
cbSelectAll.Attributes.Add("onclick", "javascript:SelectAll('" + cbSelectAll.ClientID + "')");
}
}
Yes, store the original value in a hidden field. If always starting with false, you could use JavaScript to set the hidden value to true when the user clicked the checkbox. Using JQuery, you could do:
<asp:TemplateField HeaderText="Select" ItemStyle-CssClass="Checked">
<ItemTemplate>
<asp:CheckBox ID="chkSelected" runat="server" Checked="false"></asp:CheckBox>
<asp:HiddenField iD="dh" runat="server" />
</ItemTemplate>
</asp:TemplateField>
$("#<%= Grid.ClientID %>").find(".Checked > :checkbox").each(function() {
$(this).siblings("input[type='hidden']").attr("value", "True");
});
Something like that. On Server side, parse the value and if true, then you know it changed.
HTH.
It may not be the brightest idea, but you can query the database for the current state, and the compare with what you have got from the web page during a postback button click, or something like that. Or you can go with Brians answer.
It is possible to persist a list of objects into the Viewstate and access it in a consequent postback. The only thing is that the object you are trying to persist must be defined as serializable.
Update:
The ViewState approach
I feel this may be suitable for your need, and it requires a bit of linq. You'd need to create a class as follows:
[Serializable()]
public class OptionState
{
//the id of the item
int ID {get;set;}
//state of the checkbox
bool Checked {get;set;}
}
Note the Serializable attribute. This is required for the instance to persist to the viewstate.
Add the list of options to the viewstate:
var lstOptions = (from x in <your_option_store>
select new OptionState{ID = x.ID, Checked = x.Checked}).ToList();
ViewState.Add("options", lstOptions);
Here is a bit of code that should go into your button click:
foreach(GridViewRow row in gvOptions.Rows)
{
//not writing the bit of code
//which gets the ID and the
//state of checkbox of
//the gridview row being processed
OptionState currentState = GetOptionStateObjectFromRow(row);
List<OptionState> lstStates = (List<OptionState>) ViewState["options"];
OptionState originalState = lstStates.FirstOrDefault(x => x.ID == currentState.ID);
if(currentState.Checked != originalState.Checked)
{
//the appropriate db call needs to be done here.
}
}

javascript inside updatepanel

im using javascript in asp.net gridview
<script type="text/javascript">
var currentRowId = 0;
function SelectRow()
{
if (event.keyCode == 40)
MarkRow(currentRowId+1);
else if (event.keyCode == 38)
MarkRow(currentRowId-1);
}
function MarkRow(rowId)
{
if (document.getElementById(rowId) == null)
return;
if (document.getElementById(currentRowId) != null )
document.getElementById(currentRowId).style.backgroundColor = '#ffffff';
currentRowId = rowId;
document.getElementById(rowId).style.backgroundColor = '#ff0000';
}
</script>
<script type="text/javascript">
var TargetBaseControl = null;
window.onload = function()
{
try
{
//get target base control.
TargetBaseControl =
document.getElementById('<%= this.GridView1.ClientID %>');
}
catch(err)
{
TargetBaseControl = null;
}
}
function TestCheckBox()
{
if(TargetBaseControl == null) return false;
//get target child control.
var TargetChildControl = "chkSelect";
//get all the control of the type INPUT in the base control.
var Inputs = TargetBaseControl.getElementsByTagName("input");
for(var n = 0; n < Inputs.length; ++n)
if(Inputs[n].type == 'checkbox' &&
Inputs[n].id.indexOf(TargetChildControl,0) >= 0 &&
Inputs[n].checked)
return true;
alert('Select at least one checkbox!');
return false;
}
</script>
button control:
" Width="80px" CssClass="button" />
im using ajax update panel in gridview ...i control postback level but the script is not working inside the updatepanel
In your button_clicked event, you could use this method
ScriptManager.RegisterClientScriptBlock(Control, Type, String, String, Boolean)
More info below
http://msdn.microsoft.com/en-us/library/bb350750.aspx

How do i maintain the state of my Html Controls on postback with JQuery and JSON?

I have a form with a collection of Html and ASP Server Controls. Im using JSON to preload some drop-down lists.
I want to maintain the states of these drop-down lists on postback. Im quite new to JSON, can anyone help?
If you can use HTML select element instead. Thus, you can get the selected value of select element on the server and register an hidden field to maintain the value. While you are loading the items so you can check the registered hidden field to retrieve the previous selected value.
<select id="DropDownList1" name="DropDownList1" />
<asp:Button ID="Button1" runat="server" Text="Button" />
<script type="text/javascript">
var sv = document.getElementById("SelectedValue");
var v = (sv != null && sv.value != "" ? sv.value : null);
var o = document.getElementById("DropDownList1");
for (var i = 0; i < 10; i++) {
var item = document.createElement("option");
item.innerHTML = "item" + i;
item.setAttribute("value", "item" + i);
if (("item" + i) == v)
item.setAttribute("selected", "selected");
o.appendChild(item);
}
</script>
protected void Page_Load(object sender, EventArgs e)
{
string selectedValue = Request["DropDownList1"];
if (!string.IsNullOrEmpty(selectedValue))
Page.ClientScript.RegisterHiddenField("SelectedValue", selectedValue);
}
firstly, you should create an HTTPHandler to generate the JSON and get it using getJSON method from jQuery. Lastly, you have to get the selected value on the Load event of the page and maintain the value to a HiddenField for the next time. The following code demonstares it.
public class JsonGenerator : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
JavaScriptSerializer ser = new JavaScriptSerializer();
context.Response.Write(ser.Serialize(new object[]
{
new { Text = "Item1", Value = 1 },
new { Text = "Item2", Value = 2 } ,
new { Text = "Item3", Value = 3 }
}));
}
public bool IsReusable
{
get
{
return false;
}
}
}
<select id="DropDownList1" name="DropDownList1" />
<asp:Button ID="Button1" runat="server" Text="Button" />
<script src="jquery-1.3.2.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
$.getJSON("JsonGenerator.ashx",
null,
function(r) {
var ddl = $("#DropDownList1"), hf = $("#SelectedValue");
$.each(r, function(k, v) {
ddl.append("<option value='" + v.Value + "'>" + v.Text + "</option>");
});
if (hf.length > 0)
ddl.children("[value='" + hf.val() + "']").attr("selected", "selected");
});
});
</script>
protected void Page_Load(object sender, EventArgs e)
{
string selectedValue = Request["DropDownList1"];
if (!string.IsNullOrEmpty(selectedValue))
Page.ClientScript.RegisterHiddenField("SelectedValue", selectedValue);
}
Don't let the browser do the post, do it yourself with jQuery. On the callback replace a results div with the returned html.
Assuming you've marked your form with class="ajaxform" and your results div with id="results" then something like this (not fully tested)...
// Submit form.ajaxform
// Get the returned html, and get the contents of #results and
// put it into this page into #results
var submit = function() {
$.ajax({
type: "POST",
data: $("form.ajaxform").serialize(),
success: function(data, textStatus) {
$("#results").replaceWith($("#results", $(data)));
}
});
};
$("form.ajaxform input[type=submit]").click(submit);
// I think you'll need this as well to make sure the form doesn't submit via the browser
$("form.ajaxform").submit(function () { return false; });

Resources