asp:UpdatePanel work only when other inputs are valid - asp.net

I have this UpdatePanel:
<asp:ScriptManager ID="CheckManager" runat="server" />
<asp:UpdatePanel ID="checkUsername" runat="server" UpdateMode="Conditional" >
<ContentTemplate>
<asp:Label ID="canUse" runat="server" Text=""/>
<asp:Button ID="check" runat="server" Text="Usable?" onclick="check_Click" />
<asp:TextBox ID="username" runat="server" ></asp:TextBox>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger controlid="check" eventname="Click" />
</Triggers>
</asp:UpdatePanel>
update code:
protected void check_Click(object sender, EventArgs e)
{
using (HotelEntities h = new HotelEntities())
{
UserHandle u = new UserHandle();
if (u.FindUserByUsername(h, username.Text.ToString()).Any())
{
canUse.ForeColor = Color.Magenta;
canUse.Text = "You cannot use this username";
username.Text = "";
}
else
{
canUse.ForeColor = Color.Green;
canUse.Text = "you can use this username";
}
}
}
but works only when other inputs in form (that have validations e.g. RequiredFieldValidator) are valid .
How can I fix this?

Set CausesValidation="false" for the button for which you do not want validation to be performed when the Button control is clicked.
<asp:Button ID="check" CausesValidation="false" runat="server"
Text="Usable?" onclick="check_Click" />
Button.CausesValidation Property: Gets or sets a value indicating whether validation is performed when the Button control is clicked.

You need to set the ValidationGroup property same with the button and your textbox validations etc. For example you have required field validator near the textBox1. And you have two buttons. If you dont use ValidationGroup, you wont be able to click any of them without validating your inputs.
You may
Check here to see an example

Related

how to do not postback button click

I want to prevent this phenomenon ...
Postback when button is clicked
I want to perform the result when the button is clicked and prevent the screen refresh.
<asp:Button ID="DomainSeachButton" runat="server" Text="search"
OnClick="btnDomainSearch_Click" OnClientClick="onMySearch();" Width="69px" />
function onMySearch() {
// __doPostBack("DomainSeachButton", "client");
var r = confirm("Press a button!")
if (r==true)
{
alert("You pressed OK!")
return true;
}
protected void btnDomainSearch_Click(object sender, EventArgs e)
{
if (_cDBConnect.IsValidDBInfo() == true)
{
string sql = string.Format("select * from tb_licensekey_storages where cert_domain_name like '%{0}%';", txtSearchDomain.Text.Trim());
var da = new SQLiteDataAdapter(sql, _cDBConnect.GetConnectionString());
DataTable dt = new DataTable();
da.Fill(dt);
gridViewDBInfo.DataSource = dt;
gridViewDBInfo.DataBind();
}
}
You can easily achieve this with ASP Control UpdatePanel it will not actually refresh the whole page but the the selected content of the page, for example:
<asp:ScriptManager ID="MainScriptManager" runat="server" />
<asp:UpdatePanel ID="updtpnl" runat="server">
<ContentTemplate>
<asp:Button
ID="DomainSeachButton"
runat="server"
Text="search"
OnClick="btnDomainSearch_Click"
OnClientClick="onMySearch();"
Width="69px"
AutoPostBack="true"
/>
<asp:GridView ID="GridView1" runat="server"></asp:GridView>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="DomainSeachButton" EventName="Click" />
</Triggers>
</asp:UpdatePanel>
Try changing your btnDomainSearch_Click to
$("#btnDomainSearch_Click").click( function(e){
e.preventDefault();
//Whatever
})
You can use AutoPostBack="false" in the particular button.
if AutoPostBack set false it will not send request to server otherwise it will send request to server.
<asp:Button ID="DomainSeachButton" runat="server" Text="search" AutoPostBack="false" OnClick="btnDomainSearch_Click" OnClientClick="onMySearch();" Width="69px" />
Please read this article for more information More Details

ProgressBar in UpdateProgress keeps expiring before the data is fetched

I have a GridView which shows some data and has a Button in the last column that combines the value of the 3 other columns.
I was able to refresh the GridView easily just by calling this Function GridData in the rowCommand.
protected void GridviewProcess_RowCommand(object sender, GridViewCommandEventArgs e)
{
try
{
if (e.CommandName == "More")
{
objENT = new ENT();
int index = Convert.ToInt32(e.CommandArgument.ToString());
Label locCode = (Label)GridviewProcess.Rows[index].FindControl("lbl0");
Label SurveyNo = (Label)GridviewProcess.Rows[index].FindControl("lbl2");
Button Combine = (Button)GridviewProcess.Rows[index].FindControl("btnCombine");
Combine.Enabled = false;
objENT.LocationCode = locCode.Text;
objENT.SurveyNumber = SurveyNo.Text;
objENT.ProcType = "CREATECUSTOMER";
DataSet ds = new DataSet();
ds = BLL.CdCustomer(objENT);
}
}
catch (Exception ex)
{
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alertMessage", "alert('Some Error occurred Please refresh the page')", true);
}
finally
{
Griddata();
}
private void Griddata()
{
objENT.ProcType = "PAGEGRIDDATA";
DataSet ds = BLL.ProcessGrid(objENT);
string check = ds.Tables[0].Rows[0]["TOTAL_CUSTOMER"].ToString();
GridviewProcess.DataSource = ds.Tables[0];
ViewState["Grid"] = ds.Tables[0];
GridviewProcess.DataBind();
}
After,I added this ProgressBar
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:UpdateProgress ID="UpdateProgress2" runat="server" AssociatedUpdatePanelID="UpdatePanel2">
<ProgressTemplate>
<img src="images/progress_bar.gif" style="max-width: 250px" />
</ProgressTemplate>
</asp:UpdateProgress>
<asp:UpdatePanel ID="UpdatePanel2" runat="server">
<ContentTemplate>
<asp:GridView ID="GridviewProcess" AllowPaging="true" CssClass="GridHeader" PagerSettings-Mode="NextPreviousFirstLast" PagerSettings-PreviousPageText="<-Prev  " PagerSettings-Visible="true" PagerSettings-NextPageText="  Next->"
PagerSettings-FirstPageText="<=FirstPage  " PagerSettings-LastPageText="  LastPage=>" PagerStyle-Font-Bold="true"
OnPageIndexChanging="GridviewProcess_PageIndexChanging" PageSize="12" OnRowDataBound="GridviewProcess_RowDataBound" OnRowCommand="GridviewProcess_RowCommand" runat="server" Style="text-align: center" Width="99%"
AutoGenerateColumns="false">
<Columns>
<asp:TemplateField HeaderText="Total Customers" HeaderStyle-BackColor="#99CCCC">
<ItemTemplate>
<asp:Label ID="lbl7" runat="server" Text='<%# Eval("TOTAL_CUSTOMER") %>'>
</asp:Label>
<asp:Button ID="btnCombine" CssClass="btn-primary btn" Text="Combine"
CommandArgument="<%# ((GridViewRow) Container).RowIndex %>" CommandName="More"
Style="padding-top: 1%; padding-bottom: 1%; margin-top: 1px; margin-bottom: 1px" runat="server" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</ContentTemplate>
</asp:UpdatePanel>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="btnAddi" EventName="Click" />
</Triggers>
</asp:UpdatePanel>
The ProgressBar will show but after the function GridData(){} is called it wont refresh the GridView.
I can see the changes only after,I refresh the whole page.
I don't understand whats going wrong...
I don't have any JS or CSS used for this ProgressBar..(Is that the problem?)
Found the Solution to the Problem on SO questions
UpdateProgress Timed Out before data could be processed
Actual problem was :
I have a button on my ASP.NET page, which fetches some data from my database and displays it on a GridView.
This process takes a while, so I thought I'll add an updateprogress AJAX control. Now when I click the button, the UpdateProgress Image shows up and data is being fetched from my database successfully (I checked this from some logs that I have in my DB). But there are 2 issues:
The UpdateProgress image shows only for about 2 minutes. But my ButtonClick event takes about 5 minutes to complete. Basically the UpdateProgressstops showing up even before my task is complete, which defeats its purpose.
As I found this in one of the SO Answers
As per issue most likely it is ajax timing out. Default timeout is 90 seconds. To increase that use ScriptManager's AsyncPostBackTimeout property:
<asp:ScriptManager ID="ScriptManager1" runat="server" AsyncPostBackTimeout="400">
</asp:ScriptManager>
If AJAX call is timing out, controls on the page might not work correctly so increasing timeout might solve problem (2) as well.

Run ASP.Net Custom Validator only on click of one of multiple buttons on the page

I have the following code in my ASP.Net (4.0) page, in which there are 2 buttons - 'Button1' and 'Button2', a textbox, a required field validator and a custom validator.
I would like the custom validator to fire only when 'Button1' clicked and not when 'Button2' is clicked and Button2 still needs to evaluate a required field validator. How would I make this happen?
Input 1:
<asp:TextBox id="txtCustomData" runat="server" />
<asp:CustomValidator id="CustomValidator1"
runat="server" ErrorMessage="Number not divisible by 2!"
ControlToValidate="txtCustomData"
ClientValidationFunction="CheckEven" />
<br/>
Input 2:
<asp:TextBox id="TextBox2" runat="server" />
<asp:RequiredFieldValidator ID="rfv1" runat="server" ControlToValidate="TextBox2"
ErrorMessage="* Required" ForeColor="Red" >
</asp:RequiredFieldValidator>
<br/>
<br/>
<asp:Button id="btn1" runat="server" Text="Button1" />
<br/>
<asp:Button id="btn2" runat="server" Text="Button2" />
<script language="javascript">
<!--
function CheckEven(source, args) {
var val = parseInt(args.Value, 10);
if (isNaN(val)) {
args.IsValid = false;
}
else {
args.IsValid = ((val % 2) == 0);
}
}
// -->
</script>
UPDATE 1:
While Rick's answer is a possible answer, I found another approach to handling this situation.
I can use Validation groups when both buttons need to validate 2 different validators and one of the validators is a custom validator. Set ValidationGroup="Group1" for Button1 that needs to evaluate the custom validator and ValidationGroup="Group2" for Button2 that needs to evaluate the required field validator, and include the same values for corresponding validators. There is no need to include ValidationGroup for the textboxes.
Input 1:
<asp:TextBox id="txtCustomData" runat="server" />
<asp:CustomValidator id="CustomValidator1"
runat="server" ErrorMessage="Number not divisible by 2!"
ControlToValidate="txtCustomData"
ClientValidationFunction="CheckEven" />
<br/>
Input 2:
<asp:TextBox id="TextBox2" runat="server" />
<asp:RequiredFieldValidator ID="rfv1" runat="server" ControlToValidate="TextBox2"
ErrorMessage="* Required" ForeColor="Red" ValidationGroup="Group2">
</asp:RequiredFieldValidator>
<br/>
<br/>
<asp:Button id="btn1" runat="server" Text="Button1" ValidationGroup="Group1"/>
<br/>
<asp:Button id="btn2" runat="server" Text="Button2" ValidationGroup="Group2"/>
<script language="javascript">
<!--
function CheckEven(source, args) {
var val = parseInt(args.Value, 10);
if (isNaN(val)) {
args.IsValid = false;
}
else {
args.IsValid = ((val % 2) == 0);
}
}
// -->
</script>
UPDATE 2:
If you end up using custom javascript in OnClientClick event of the button, then you need to be careful with your javascript else you might end up having your button never postback even when data is valid.
For example if you have written a custom javascript function called 'ValidateData( )' then first make sure that it always has return true or return false statement in it, and second your OnClientClick should use this function in the manner shown below. Most developers will simply use OnClientClick = "return ValidateData();" which will make the ASP.Net button to NEVER perform an ASP.Net post back even when the data is evaluated as valid, since the default __doPostBack JavaScript function in ASP.Net will never get called (assuming UseSubmitBehavior="false" for this button, if UseSubmitBehavior="true" then __doPostBack is not used and button will postback).
<asp:Button id="btn1" runat="server" Text ="Button1"
OnClientClick="var r = ValidateData(); if (!r) { return false; } " />
<script type=<script type="text/javascript">
function ValidateData( )
{
var x = document.getElementById('xy1');
if(x.value == '1')
{
return false;
}
return true;
}
</script>
Include the CausesValidation attribute and set it to False. Your button will not trigger validation.
http://msdn.microsoft.com/en-us/library/system.windows.forms.control.causesvalidation(v=vs.110).aspx
<asp:Button id="btn2" runat="server" Text="Button2" CausesValidation="False"/>

UpdatePanel only update from events

hello every one my problem goes like this
i have two updatepannels
<asp:UpdatePanel ID="new_word_panel_UpdatePanel" runat="server" UpdateMode="Conditional">
<ContentTemplate >
<asp:Panel ID='new_word_panel' runat="server">
<asp:Button ID='new_word_btn' runat="server" Text='give me a new word' Visible='false' OnClick='GenNewWord' />
</asp:Panel>
</ContentTemplate>
</asp:UpdatePanel>
<asp:UpdatePanel ID="UpdatePanel1" runat="server" >
<ContentTemplate >
<asp:Button ID='Button8' runat="server" Text='hide' OnClick='hidegive' />
</ContentTemplate>
</asp:UpdatePanel>
the first updatepanel UpdateMode is set to Conditional so i can
update is content from the second updatepanel asp:Button ID='Button8' OnClick='hidegive'
event easily by using the Update() method.
this is the eventhandler:
protected void hidegive(object sender, EventArgs e)
{
if (new_word_btn.Visible == true)
new_word_btn.Visible = false;
else
new_word_btn.Visible = true;
**new_word_panel_UpdatePanel.Update();**
}
my problem is that i cant update the first UpdatePanel from reguler method on my page
although i am using the Update() method, i have try to update panel from this
method and nothing hapeens:
void PlayerWinEventHandler(object sender,Game.PlayerWinEventArgs e)
{
Session["score"] = int.Parse(Session["score"].ToString()) + 10;
UpdateScore();
if (new_word_btn.Visible == true)
new_word_btn.Visible = false;
else
new_word_btn.Visible = true;
new_word_btn.Text = "zibi";
**new_word_panel_UpdatePanel.Update();**
}
thanks for your help...
Why dont you use Triggers in your first update panel.
<Triggers>
<asp:AsyncPostBackTrigger ControlID="Button8" EventName="Click"/>
</Triggers>

How to set the target control id of ajax modelpop up extender to a run time button created id?

I am creating a button at run time and on it's click i want to open a ajax model pop up.
But i am unable to set model pop up's target control id to this run time created button id.
Could some body suggest me how to achieve this? or any alternate way exist?
My code is as following.
This is how i am creaing a run time button.
protected void grdSurveyMaster_ItemCreated(object sender, GridItemEventArgs e)
{
if (e.Item is GridFooterItem)
{
GridFooterItem footerItem = (GridFooterItem)e.Item;
// RadScriptManager1.RegisterAsyncPostBackControl(btn);
Button btn = new Button();
btn.Text = "Take a new survey";
btn.CommandName = "newAssess";
btn.Click += new System.EventHandler(grdMasterbtnClick);
footerItem.Cells[2].Controls.Add(btn);
//ModalPopupExtender1.TargetControlID = "btn";// Convert.ToString(Page.FindControl(Convert.ToString(btn.ClientID)));
}
}
And following is my HTMl
<asp:UpdatePanel ID="updatepanel1" runat="server">
<ContentTemplate>
<cc1:ModalPopupExtender CancelControlID="btnCancel" PopupControlID="modelPopUp" ID="ModalPopupExtender1"
runat="server" TargetControlID="btnDefault">
</cc1:ModalPopupExtender>
<asp:Button ID="btnDefault" runat="server" Visible="false" />
<asp:Panel ID="modelPopUp" runat="server" Visible="false" BackColor="AliceBlue">
<p>
These items will be permanently deleted and cannot be recovered. Are you sure?
</p>
<asp:Button ID="btnOk" Text="OK" runat="server" />
<asp:Button ID="btnCancel" Text="Cancel" runat="server" />
</asp:Panel>
</ContentTemplate>
</asp:UpdatePanel>
Well you're doing right setting the Popup's TargetControl an invisible unused button. Now the best way to show/hide your popup is from Javascript. For this you have to set the behaviorid="someString" of your ModalPopupExtender and create a javascript function like this:
function ShowModalPopup(behaviourId) {
$find(behaviourId).show();
}
Then you can assign the javascript function to a button:
btn.OnClientClick = String.Format("ShowModalPopup('{0}')",
ModalPopupExtender1.behaviorid);

Resources