validation on postback if gridview is empty - javascript

I am trying to provide an ok cancel popup 'if' the gridview has no rows and I thought this would work like a client script, but when I hit ok the control skips rest of the method. Is there anyway I could perform this validation or alert and move the control to the next statement?
protected void btnRunD_Click(object sender, EventArgs e)
{
try
{
int iESStatus = 0;
int iRunStatus = 0;
ApplicationUser au = (ApplicationUser)Session["ApplicationUser"];
if (UploadFileGrid.Rows.Count <= 0)
{
ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "err_msg", "confirm('No new data files have been uploaded. Are you sure you want to run EYDS Processing Module?');",
//true);
}
if (au.RoleID != 2) //RoleID is not Admin!
{
ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "err_msg", "alert('You do not have enough privileges to use this functionality!');",
true);
}
else
{.........}
}
The part I'm having difficulty with is here:
I am trying to provide an ok cancel popup 'if' the gridview has no rows
if (UploadFileGrid.Rows.Count <= 0)
{
ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "err_msg", "confirm('No new data files have been uploaded. Are you sure you want to run?');",
}

Supposing your button is something like this:
<asp:Button ID="btnDoSomething" runat="server" Text="Do Something" OnClientClick="return GetConfirmation();" OnClick="btnDoSomething_Click" />
then add a javascript function as below:
function GetConfirmation() {
var rowscount = document.getElementByID(<%=UploadFileGrid.ClientID%>).rows.length;
return rowscount > 0 || confirm('No new data files have been uploaded. Are you sure you want to run?');
}
then it'll be postbacked just when the user press ok when confirm button is shown.

You can do it using javascript or jquery:
$("#<%=btnApprove.ClientID %>").click(function () {
if ($("#<%=UploadFileGrid.ClientID %> ").find("tr").length == 0) {
if (confirm('No new data files have been uploaded. Are you sure you want to run?')) {
return true;
}
else {
return false;
}
}
});
and when user press OK,your page will be postbacked,you can write the code which you want to execute after that.
I hope this code will help you.

Related

Javascript Popup from Code Behind Without Button Onclick Action

I have read numerous threads and cannot figure this one out as they all relate to calling a javascript with a button click. I have a simple javascript popup that I want to call during my vb code in an asp.net project. Each time I call the javascript, the program continues on, and my variable from the popups do not get calculated.
I need the program to stop, wait for the popup reply, and then based upon the reply, continue on. What am I missing? The first one runs fine as it is conditional based upon a button OnClientClick method, but the next two are in the code behind. I need the program to stop, wait for a response, and continue based upon the response. This doesn't happen and using ScriptManager.RegisterStartupScript or other javascript calls as they aren't stopping the program to wait for the response. The second two do not have a button click event to trigger them, only a programming code call.
HTML Code:
<script type="text/javascript">
function Payment() {
var payment_value = document.createElement("INPUT");
payment_value.type = "hidden";
payment_value.name = "payment_value";
if (confirm("Are you sure you want To Cancel this Payment?")) {
payment_value.value = "Yes";
} else {
payment_value.value = "No";
}
document.forms[0].appendChild(payment_value);
}
</script>
<script type="text/javascript">
function LateFee() {
var latefee_value = document.createElement("INPUT");
latefee_value.type = "hidden";
latefee_value.name = "latefee_value";
if (confirm("This payment is over 30 days, do you want to add a Late Fee ($99.00) to this incident?")) {
latefee_value.value = "Yes";
} else {
latefee_value.value = "No";
}
document.forms[0].appendChild(latefee_value);
console.log(latefee_value)
}
</script>
<script type="text/javascript">
function LateFeePrint() {
var latefeeprint_value = document.createElement("INPUT");
latefeeprint_value.type = "hidden";
latefeeprint_value.name = "latefeeprint_value";
if (confirm("Late Fee Updated Successfully, do you want to print a Late Fee Notice?")) {
latefeeprint_value.value = "Yes";
} else {
latefeeprint_value.value = "No";
}
document.forms[0].appendChild(latefeeprint_value);
}
</script>
<h2><%: Title %></h2>
<p class="text-danger">
<asp:Literal runat="server" ID="Literal1" />
</p>
VB,net Code:
If NumDays > 30 And TempLateFee <> "$99.00" Then
Dim LateFeeValue As String = Request.Form("latefee_value")
'Call Javascript and popup the modal
ScriptManager.RegisterStartupScript(Me, Page.GetType, "LateFeeCall", "LateFee()", True)
'use the result to calculate the late fee
If LateFeeValue = "No" Then
ElseIf LateFeeValue = "Yes" Then
AccountBalance = 0
Call UpdateLateFee()
Call GetAlarmInfo()
Call LoadAlarmInfo()
Call LoadBalanceInfo()
End If
End If

call function from code behind in javascript without postback

I have a list of customers that the user can choose from. When they select a customer, I need to load the contacts of that customer. I needed to call the function from JavaScript so I added a button:
<asp:Button ID="btnSample" runat="server" style="float:right;display:none" OnClick="btnSample_Click" />
and that button then gets triggered from my JavaScript function:
function OnGetCustomer(result){
document.getElementById('lblCustID').innerHTML = result.ID;
document.getElementById('lblCustName').innerHTML = result.Name;
document.getElementById("btnSample").click();
}
Code behind to load the contacts:
protected void btnSample_Click(object sender, EventArgs e)
{
RateSheet r = new RateSheet(ID, Company.Current.CompanyID);
if (!string.IsNullOrEmpty(lblCustID.Text))
{
Customer c = new Customer(int.Parse(lblCustID.Text));
bool e2 = false;
foreach (Customer.CustomerContact cc in c.Contacts)
{
HtmlGenericControl li = new HtmlGenericControl("li");
CheckBox cb = new CheckBox();
cb.ID = "cbCustContact_" + cc.ID;
cb.Checked = true;
if (!string.IsNullOrEmpty(cc.Email))
{
cb.Text = cc.Email;
cb.TextAlign = TextAlign.Right;
li.Controls.Add(cb);
ulCustContacts.Controls.Add(li);
}
}
}
}
I need the value from lblCustID to find the customer's contacts. The problem is the button causes postback and I lose the customer I selected so lblCustID always comes back as zero. How do I stop postback so I don't lose any values?
Is lblCustID a label or an input? The only* controls in which changes are preserved in postback are inputs. You can use <asp:HiddenField /> or any <input runat="server" ... /> to send information for the code behind to work with.
*Along with other controls such as dropdownlists etc
You can use asynchronous call to achieve that:
Set AutoPostback="false" to prevent the button to cause postback onclick
<asp:Button ID="btnSample" runat="server" style="float:right" AutoPostback="false" />
Or just add a raw HTML button (ATTENTION: add a type="button" or this will cause a postback):
<button id="btnSample" type="button">Click</button>
Then add an event listener to this button and execute the ajax call:
$(document).on('click', '[id$=btnSample]', function() {
ajax({
url: 'path/to/handler',
method: 'POST',
data: { key: 'value', ... },
success: function(data) {
OnGetCustomer(data);
},
error: function() {
console.log('Error on ajax call!');
}
});
});
NOTE: You have to move your cobebehind code into a generic handler to handle the ajax call and return the result

Need a javascript function to identify the which textbox used while clicking save button

I have 3 textboxes in 3 tabs of same ASP.net page and corresponding 3 javascript functions of same functionality. Presently I am using 3 different functions for three textboxes. I need only a single javascript function instead of three. Please help me
<asp:TextBox ID="textBox1" runat="server" ValidationonGroup="abcd"></asp:TextBox>
<asp:CustomValidator ID="ID1" runat="server" ValidationGroup="abcd" ControlToValidate="textBox1" ErrorMessage="message" ClientValidationFunction="fname"></asp:CustomValidator>
Javascript functon
function fname(sender, args) {
var x = document.getElementById('<%=txtBox1.ClientID%>').value;
if (some condition) {
args.IsValid = false;
} else {
args.IsValid = true;
}
}
One way to do it would be checking which textbox value != "" and execute the send based on this
eg your onClick handler could contain this.
if(document.getElementById('<%=txtBox1.ClientID%>').value != ""){
do this
} else if (document.getElementById('<%=txtBox2.ClientID%>').value != ""){
do this
} else {
do this
}
Why don't you make one function that receives text box ID and call it from other 3:
function fname(textBoxID, sender, args) {
var x = document.getElementById(textBoxID).value;
if (some condition) {
args.IsValid = false;
} else {
args.IsValid = true;
}
}
When you call it for first text box, just pass '<%=txtBox1.ClientID%>' as first parameter. Same way, pass '<%=txtBox2.ClientID%>' for second text box...
There is another solution, you can find it more in detail here: Passing value from CustomValidator
In short it goes like this: use sender.id to get the id of the CustomValidator. Then so long as the validator's id is the id of the TextBox with a prefix of 'Validator_', I can use a javascript replace to get rid of the 'Validator_', therefore finding out the TextBox Id.

Call Javascript Function From Server Side C#

I created a report that shows a list of manifests. The user can search through this list by the manifest number. When the code is running the search, I'm displaying a Gif:
But this Gif won't disappear once the search is finished. I can see the correct record is being displayed so the search is over, but the Gif stays on the screen.
The function is called when the search button is clicked.
<asp:Button runat="server" CssClass="btnSearch loading" ID="btnSearch" Text="Search" OnClick="btnSearch_Click" OnClientClick="ShowLoadingGif()" ToolTip="Search" />
<div id="dvLoading">
<table>
<tr>
<td id="tdLoadingSave"><img src="/images/loading.gif" alt="Loading..." title="Loading..." /></td>
</tr>
</table>
</div>
function ShowLoadingGif() {
closefiltermenu();
$("#tdLoadingSave").html($("#tdLoadingSave").html() + "<br/> Please wait, manifest list is loading");
$('#dvLoading').fadeIn("500");
}
function CloseLoadingGif() {
$('#dvLoading').fadeOut("500");
}
The search is then run from another function:
protected void Search()
{
string Field = ddlSearchBy.SelectedValue;
string SearchString = txtSearchBy.Text;
string[] SearchFields = null;
string[] SearchStrings = null;
if (!string.IsNullOrEmpty(SearchString) && Field != "null")
{
SearchFields = new string[] { Field };
SearchStrings = new string[] { SearchString };
}
List<lookupManifestAnalysis> main = lookupManifestAnalysis.SearchManifestItems(Company.Current.CompanyID,
SearchStrings,
SearchFields);
gvResults.DataSource = main;
gvResults.DataBind();
udpResults.Update();
ClientScript.RegisterStartupScript(GetType(), "Search", "CloseLoadingGif();", true);
}
But how do I stop the Gif displaying once the search is over?
ScriptManager.RegisterStartupScript(this, GetType(), "CloseLoadingGif","CloseLoadingGif();", true);
OR
If you are dealing with asp.net UpdatePanel and UpdateProgress, use the following code:
ScriptManager.RegisterStartupScript(myUpdatePanelID,myUpdatePanelID.GetType(),"CloseLoadingGif", "CloseLoadingGif();", true);
When you are executing your code in Server side ASP you should not use client side function for showing or hiding elements. Instead try using Ajax Controls from .Net.
You will need to use AJAX Progress control. Here have a look :
https://msdn.microsoft.com/en-us/library/bb386421.aspx

Validation summary message pops up twice

I have validation controls in my page and I am using Validation summary message box to display the validation messages,the javascript function shown below worked for me but the problem is I am using this javascript function on OnClientClick event of the button and when I click the button with form controls not been filled its displaying the validation summary message box as expected but when i close the summary box it's getting displayed again and i need to close the message box to disappear, means i have to do two clicks everytime. Can somebody correct me what am I doing wrong.
Here is what I am doing:-
<asp:Button ID="SubmitButtonOne" runat="server" Text="Submit" OnClick="SubmitButtonOne_Click"
ValidationGroup="Cases" ClientIDMode="Static" OnClientClick="PleaseWaitShow()" />
Here is the javascript function:
function PleaseWaitShow() {
var isPageValid = true;
// Do nothing if client validation is not active
if (typeof (Page_Validators) != "undefined") {
if (typeof (Page_ClientValidate) == 'function') {
isPageValid = Page_ClientValidate();
}
}
if (isPageValid) {
document.getElementById('SubmitButtonOne').value = "Processing...";
}
}
code behind:
protected void SubmitButtonOne_Click(object sender, EventArgs e)
{
try
{
// some functionality
}
catch (Exception)
{
//show errror message
}
}
It is expected behavior.
Once Page_ClientValidate is fired due to your explicit call inside PleaseWaitShow method and second is an implicit call made by the PostBack button click.
And so you are seeing two times the ValidationSummary message box.
I don't have a solution to circumvent this but will update if something strikes.
Note: One thing I would like to point out is since you have ValidationGroup="Cases" on your submit button you should pass that to your Page_ClientValidate method.
Update 1: One way I can think of is trying something like this:
1: OnClientClick="return PleaseWaitShow();"
2: return isPageValid from PleaseWaitShow():
function PleaseWaitShow() {
var isPageValid = true;
....
....
....
return isPageValid;
}
No, it is not the expected behavior. Rather, it's a bug in ASP.NET validation JS code.
The ValidationSummaryOnSubmit function loops over all summaries, and for each summary, loops over all validators. If not group is specified, then each validator's message is appended, resulting in 2 (3, 4, 5?) repetitions of the same messages.
I solved the problem by fixing the function (staring at line 53 or so):
....
for (i = 0; i < Page_Validators.length; i++)
{
var validator = Page_Validators[i];
if (validator.validationGroup != null && summary.validationGroup != null)
{
if (validator.validationGroup != summary.validationGroup) continue;
}
if (!validator.isvalid && typeof (validator.errormessage) == "string")
{
s += pre + validator.errormessage + post;
}
}
....
if you use Page_ClientValidate method, you should set causevalidation to false. CausesValidation="false"
because Page_ClientValidate is already doing this for button or control you validate
Please remove ValidationGroup of Button. Only user for ValidationSummary
Like:
<asp:TextBox ID="txtName" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="rqvName" runat="server" ControlToValidate="txtName" ErrorMessage="Please enter Name" ValidationGroup="SaveName"> </asp:RequiredFieldValidator>
<asp:Button ID="btnSave" runat="server" OnClientClick="DisableButton();" Text="Save this Name" ></asp:Button>
<asp:ValidationSummary ID="valSaveName" runat="server" ValidationGroup="SaveName" ShowMessageBox="true" ShowSummary="false" />
Thanks

Categories

Resources