Javascript Function Not Firing from C# Function ASP.Net - javascript

I am using a asp:Repeater control while trying to develop a screen as shown below:
Submit form
When ToolId is entered on the TextChanged Event I am getting value for MaxToolLife stored as double. When an user enter values greater than the stored value for the field ToolLife I need to show Yes/No popup stating "The value entered is greater than existing value. Do you want to proceed?" on button submit or textchanged event.
Currently I am using the below code but I am not getting Javascript alert.
protected void btnSubmit_Click(object sender, EventArgs e)
{
if (Convert.ToDouble(txtToolLifeAchieved.Text) > maxToolLife)
{
Page.ClientScript.RegisterStartupScript(Page.GetType(), "Confirm", "javascript:Confirm();", true);
if (hdnconfirm.Value=="Yes")
{
row["Pcs Produced"] = Convert.ToDouble(txtToolLifeAchieved.Text);
}
else
{
txtToolLifeAchieved.Text = "1";
txtToolLifeAchieved.Focus();
return;
}
}
else
{
row["Pcs Produced"] = Convert.ToDouble(txtToolLifeAchieved.Text);
}
}
In place of Page.ClientScript I have also used "Page.ClientScript.RegisterClientScriptBlock" & /ScriptManager.RegisterStartupScript. Nothing is working as of now. I am unable to call the javascript function from code behind. Any immediate response would help a lot.
The confirm() is as shown below:
function Confirm()
{
var confirm_value = document.createElement("INPUT");
confirm_value.type = "hidden";
confirm_value.name = "confirm_value";
if (confirm("The data already exists. Do you want to Overwrite data?"))
{
confirm_value.value = "Yes";
document.getElementById('<%= hdnconfirm.ClientID %>').value = "Yes";
}
else
{
confirm_value.value = "No";
document.getElementById('<%= hdnconfirm.ClientID %>').value = "No";
}
document.forms[0].appendChild(confirm_value);
}

So, I will stick to your original code, and this is how your server method should look like:
// This is just to illustrate the limit
private const double MaxToolLife = 100;
protected void btnSubmit_Click(object sender, EventArgs e)
{
// Check the limit first
if (Convert.ToDouble(txtToolLifeAchieved.Text) > MaxToolLife)
{
// If the hidden field is empty show the confirm
// By default the hidden field is empty, it means that user just
// pressed the submit button but not the confirmation dialog
if (string.IsNullOrWhiteSpace(hdnconfirm.Value))
{
ClientScript.RegisterStartupScript(this.GetType(), "Confirm", "Confirm();", true);
return;
}
// If the hidden field is not empty, this postback was made by the confirm
// So check for the value of the hidden field
if (hdnconfirm.Value == "Yes")
{
// Handle 'Yes'
}
else
{
// Handle 'No'
}
}
else
{
// The limit is not reached
}
}
I omitted your specific code above. This is how the form looks like:
<form id="form1" runat="server">
<!-- Hidden field for the confirm result -->
<asp:HiddenField ID="hdnconfirm" runat="server" />
<!-- Text box for user input -->
<asp:TextBox ID="txtToolLifeAchieved" runat="server"></asp:TextBox>
<!-- Submit button -->
<asp:Button ID="btnSubmit" runat="server" Text="Submit" OnClick="btnSubmit_Click" />
</form>
Than right before the form tag in your page, place your javascript function, it must be place before the form tag, because calling ClientScript.RegisterStartupScript will append the script at the end of your form tag and that time your Confirm() method be defined. And this is your javascript method:
<script type="text/javascript">
function Confirm() {
if (confirm("The data already exists. Do you want to Overwrite data?")) {
document.getElementById('<%= hdnconfirm.ClientID %>').value = "Yes";
}
else {
document.getElementById('<%= hdnconfirm.ClientID %>').value = "No";
}
// Post the form back to server using the '__EVENTTARGET' hidden field
var form = document.getElementById("form1");
// Create hidden field
var input = document.createElement("input");
input.setAttribute("type", "hidden");
input.setAttribute("name", "__EVENTTARGET");
input.setAttribute("id", "__EVENTTARGET");
input.setAttribute("value", '<%= btnSubmit.ClientID %>');
// Append input to the form element
form.appendChild(input);
// Submit the form
form.submit();
}
</script>
There is no need to create another hidden field for the confirmation result. Instead just right after the confirm you need to create hidden field with name set to __EVENTTARGET, and the value of that hidden field must be the name of the submit button, and than just call submit method on the form. This will case postback to the server, with the hdnconfirm set to Yes or No while your btnSubmit_Click method will be executed.

Related

asp.net webforms issues with RegularExpressionValidator, Javascript, Validation

I am working on a web forms project. I have many phone number fields. I have added both a RequiredFieldValidator and a RegularExpressionValidator to each phone field as well as a PhoneNumberFormatter() javascript function to the oninput event for each asp:Textbox.
The main way to express my problem is that the RegualrExpressionValidator will still allow the asp:Button to submit the page even when there is an incomplete phone number in those boxes.
I have added a DoPost() function to the buttons OnClientClick event that cycles through all the validators and turns all the inputs red that have not met their validator's parameters. But still the RegularExpressionValidator is still allowing incomplete phone numbers to pass through when the button is pressed.
The only way that I have found to overcome this is by adding a function to agressively validate the phone length as needed, and use the setCustomValidity javascript function, which works to keep the page from submitting with incomplete numbers, but for some reason that undoes all the other boxes that I turned red for not passing their validation.
For some reason, if I click submit twice, THEN the boxes that are supposed to turn red will finally turn red. This was not a problem until I added the setCustomValidity to the phone inputs that were incomplete, otherwise the fields would turn red when expected on the first click, BUT incomplete partial phone numbers were passing through.
Basically, I want to know what I can do with basic validators and javascript to ensure the phone number is the length I need and wont interfere with the other function of turning the other required fields red when they need to.
Markup for phone input
<div class="form-group">
<label>School Contact Administrator Phone:</label>
<asp:TextBox runat="server" ID="MainContactPhone" CssClass="form-control" TextMode="Phone"
oninput="PhoneNumberFormatter(ContentPlaceHolder1_MainContactPhone); ReValidateText(ContentPlaceHolder1_MainContactPhone)"/>
<asp:RegularExpressionValidator ID="MainContactRegVal" runat="server" CssClass="text-danger"
ErrorMessage="Not a valid phone number" ControlToValidate="MainContactPhone"
ValidationExpression="^[01]?[- .]?(\([2-9]\d{2}\)|[2-9]\d{2})[- .]?\d{3}[- .]?\d{4}$" />
<asp:RequiredFieldValidator runat="server" ValidationGroup="ValGro" ID="MainContactVal"
ControlToValidate="MainContactPhone" InitialValue=""
Text="Required Field" CssClass="text-danger" />
</div>
Markup for Submit Button
<asp:Button runat="server" ID="IntakeTypeSubmit" Text="Next"
OnClick="IntakeTypeSubmit_Click"
CssClass="btn btn-info" ValidationGroup="ValGro" OnClientClick="DoPostIntro()" />
JS for DoPostIntro()
function DoPostIntro() {
try {
//DoPost(); //I have tried changing the order of when I do the base DoPost()
var phone = document.getElementById('ContentPlaceHolder1_MainContactPhone');
var reqVal = document.getElementById('ContentPlaceHolder1_MainContactVal');
var regVal = document.getElementById('ContentPlaceHolder1_MainContactRegVal');
ValidatePhone(phone, reqVal, regVal);
DoPost();
} catch (Error) {
alert(Error);
}
}
JS for base DoPost()
function DoPost() {
try {
for (var i = 0; i < Page_Validators.length; i++) {
var val = Page_Validators[i];
var ctrl = document.getElementById(val.controltovalidate);
if (ctrl != null && ctrl.style != null) {
if (!val.isvalid) {
ctrl.style.backgroundColor = '#FFAAAA';
}
else {
ctrl.style.backgroundColor = '';
}
}
}
document.getElementById('Warning').style.visibility = 'visible';
} catch (Error) {
alert(Error);
}
}
JS for ValidatePhone
function ValidatePhone(input, reqVal, regVal) {
if (input.value == '' && (reqVal.enabled == true || reqVal.enabled === undefined)) {
input.style.backgroundColor = '#FFAAAA';
ValidatorEnable(reqVal, true);
reqVal.style.visibility = 'visible';
}
if (input.value.length < 14 && (regVal.enabled == true || regVal.enabled === undefined)) {
input.style.backgroundColor = '#FFAAAA';
ValidatorEnable(regVal, true);
input.setCustomValidity("Invalid Phone Number");
regVal.style.visibility = 'visible';
} else {
input.setCustomValidity("");
regVal.style.visibility = 'hidden';
}
}
C# that registers the DoPostIntro()
Page.ClientScript.RegisterOnSubmitStatement(this.GetType(), "val", "DoPostIntro();");

Trigger JavaScript Confirm() from code behind

I am working on a Asp.Net application, currently i am trying to trigger a JavaScript Confirm() popup from the code behind. I would like to popup without clicking any button_click event.
IF not blnResult then
popup message with OK& CANCEL
IF OK THEN Exit Sub
ELSE
no display
END IF
I tried to do below things and it's not firing popup, please assist.
1) Created a button in ASPX
<asp:Button ID="btnConfirm" runat="server" Text="Delete-All" OnClick="btnConfirm_Click" OnClientClick="Confirm()"/>
JavaScript function
<script language="javascript" type = "text/javascript">
function Confirm() {
var confirm_value1 = document.createElement("INPUT");
confirm_value1.type = "hidden";
confirm_value1.name = "confirm_value";
if (confirm("Do you want to delete all records?")) {
confirm_value1.value = "Yes";
} else {
confirm_value1.value = "No";
}
document.forms[0].appendChild(confirm_value1);
}
</script>
Code behind,
Public function GetConfirmation()
btnConfirm_Click(btnConfirm, EventArgs.Empty)
End Sub
Above line isn't firing the popup for me.
If I have understood correctly then probably you want to call your code behind click event only when user confirms by click on yes. There are many of ways doing this. I have listed few of them. Choose which ever suits best for you.
Don't know why you have created a hidden input field. What is the purpose of creating it. In case you don't need hidden input filed you can try these out.
Confirmation in HTML Tag
<asp:Button ID="btnConfirm" runat="server" Text="Delete-All" OnClick="btnConfirm_Click" OnClientClick="return confirm('Do you want to delete all records?');"/>
Confirmation in JavaScript
<asp:Button ID="btnConfirm" runat="server" Text="Delete-All" OnClick="btnConfirm_Click" OnClientClick="Confirm();"/>
<script language="javascript" type="text/javascript">
function Confirm() {
return confirm("Do you want to delete all records?");
}
</script>
Or
<script language="javascript" type="text/javascript">
function Confirm() {
var result = confirm("Do you want to delete all records?");
return result;
}
</script>
If you do need to keep hidden input field then use below.
<script language="javascript" type="text/javascript">
function Confirm() {
var confirm_value1 = document.createElement("INPUT");
confirm_value1.type = "hidden";
confirm_value1.name = "confirm_value";
var result = confirm("Do you want to delete all records?");
confirm_value1.value = result ? "Yes" : "No";
document.forms[0].appendChild(confirm_value1);
return result;
}
</script>
Just modify your javascript function.
<script language="javascript" type = "text/javascript">
function Confirm() {
var confirm_value1 = document.createElement("INPUT");
confirm_value1.type = "hidden";
confirm_value1.name = "confirm_value";
if (confirm("Do you want to delete all records?")) {
confirm_value1.value = "Yes";
} else {
confirm_value1.value = "No";
}
document.forms[0].appendChild(confirm_value1);
return false;//this will prevent submit click.
} </script>
just add return statement at last line of function.
return false;
I hope this solution will help you.

Javascript - textbox validation on ASP.Net button click

When I click the asp.net button as per the below code, it goes into my js file, and gets the function as I need, however if it fails validation it still goes through with the postback as if it were valid.
the asp.net button
<asp:Button ID="bttnSend" runat="server" OnClientClick="DoValidation()" Text="Send" CssClass="btn btn-primary margin30" />
the javascript
function DoValidation(parameter) {
console.log("validating");
var valid = true;
var emailTo = document.getElementById("txtEmailTo").value;
if (emailTo.length < 1) {
alert("Please select at least one recipient to send an email to");
valid = false;
}
console.log(valid);
if (valid == true) {
__doPostBack('bttnSend', parameter);
}
};
I would be grateful if someone could please tell me what i need to change and what to so that the validation doesnt allow the postback if it fails.
thanks
You need to prevent the default action of button when condition fails.
Modify your function to return true/false
function DoValidation(parameter) {
var valid = true;
var emailTo = document.getElementById("txtEmailTo").value;
if (emailTo.length < 1) {
alert("Please select at least one recipient to send an email to");
valid = false;
}
return valid;
};
The use the return value
<asp:Button ID="bttnSend" runat="server" OnClientClick="return DoValidation()" Text="Send" CssClass="btn btn-primary margin30" />

Disable Submit Button during Postback

I'm trying to disable the button during form submission but not able to do so. Here is the javascript code
<script type="text/javascript">
function Validate(b)
{
function stuff()
{
var temp = document.getElementById("<%=txt_stuff.ClientID %>").value;
var val = /^[a-zA-Z0-9 ]+$/
if(temp=="")
{
alert("Please Enter Stuff");
return false;
}
else if(val.test(temp))
{
return true;
}
else
{
alert("Name accepts only spaces and charcters");
return false;
}
}
function price()
{
var temp2 = document.getElementById("<%=txt_price.ClientID %>").value;
var val2 = /^[0-9 ]+$/
if(temp2=="")
{
alert("Please Enter Price");
return false;
}
else if(val2.test(temp2))
{
return true;
}
else
{
alert("Price accepts only Number");
return false;
}
}
if(stuff() && price())
{
b.disabled = true;
b.value = 'Submitting...';
return true;
}
else
{
return false;
}
}
</script>
Here is the button code
<asp:Button ID="Button2" runat="server" Text="Add Record" OnClientClick = "return Validate(this)"
onclick="Button2_Click" />
The button gets disabled but the value isn't submitted into the database.
Database update code is
protected void Button2_Click(object sender, EventArgs e)
{
System.Threading.Thread.Sleep(500);
SqlConnection con = new SqlConnection();
con.ConnectionString = "Data Source=DTPXP-77A;Initial Catalog=practice;Integrated Security=true";
con.Open();
SqlCommand cmd = new SqlCommand("insert into expense values(#person,#item,#expdate,#price)", con);
cmd.Parameters.Add("#person", SqlDbType.VarChar);
cmd.Parameters.Add("#item", SqlDbType.VarChar);
cmd.Parameters.Add("#expdate", SqlDbType.DateTime);
cmd.Parameters.Add("#price", SqlDbType.Int);
cmd.Parameters["#person"].Value = droplist_person.SelectedItem.ToString();
cmd.Parameters["#item"].Value = txt_stuff.Text;
cmd.Parameters["#expdate"].Value = DateTime.Now.ToString();
cmd.Parameters["#price"].Value = txt_price.Text;
cmd.ExecuteNonQuery();
InsertHistory();
Response.Redirect("Add.aspx");
}
remove the UseSubmitBehavior="false" attribute?
and you dont need to return anithing in the javascript (return false is used to cancel a postback)
I think it's the way you are inserting the items into the database since you said that it disables the button but doesn't insert the database. So to me, that means the event is firing but something is wrong with the way you are inserting. This is how my buttons look, using your code..
protected void Button2_Click(object sender, EventArgs e)
{
string person = droplist_person.SelectedItem.Text;
string item = txt_stuff.Text;
string expdate = DateTime.Now.ToString();
string price = txt_price.Text;
System.Threading.Thread.Sleep(500);
SqlConnection con = new SqlConnection("Data Source=DTPXP-77A;Initial Catalog=practice;Integrated Security=true");
con.Open();
SqlCommand cmd = new SqlCommand("INSERT INTO (expense person, item, expdate, price) VALUES (#person, #item, #expdate, #price)", con);
cmd.Parameters.AddWithValue("#person", person);
cmd.Parameters.AddWithValue("#item", item);
cmd.Parameters.AddWithValue("#expdate", expdate);
cmd.Parameters.AddWithValue("#price", price);
cmd.ExecuteNonQuery();
InsertHistory();
Response.Redirect("Add.aspx");
Button2.Enabled = false; //you can disable the button one the button click as well.
Page.ClientScript.RegisterStartupScript(this.GetType(), "Call my function", "mess();", true);
}
I would also surround that in a try/catch. Also, as far as I know, the Add is the "old" way of inserting items into the database. AddWithValue is going to be the best way since you are inserting items from drop downs and from text boxes. I think this is the where the problem lies. You can also put the connection inside the connection inside the SqlConnection like above to "clean" things up a bit. As to your "2nd" question, I'm not completely sure what you mean, but I hope this solves the problem to your 1st question.
EDIT: Added the disabling of the button since it was described in the title.
EDIT 2: Also, remove the UseSubmitBehavior="false" and the OnClientClick. Instead, you can call the message in the behind code.. Look above for example.
EDIT 3: From what I understand then, you will want to keep what the code the inserts the values. So keep the OnClientClick = "return Validate();" And then in your button click, disable the button. Then you will want to add if(!PostBack) to the page load, like so.. This will enable the button on the page load if the postback has happened. So what will be happening is that you disable the button, then once it posts back, it will be re-enabled.
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
Button2.Enabled = true;
}
}

how to capture javascript var value into asp.net page

I have an asp.net page on which at a click on Button (btn1), i want to show message box asking user a question "Do you want to overwrite ?" with button "Ok/Overwrite" and "Cancel" , and based on user response , i will have to update my database.
So i was trying to accomplish it using Javascript Confirm function
var r = Confirm('Do you want to overwrite ?)
but now i have to capture this Var r into my page so that i can update my database accordingly
any help how can i do it ?
On this scenario, you don't need to pass in the value of r to the server; you simply don't postback.
Just have something like this:
<asp:button id="btn1" runat="server" OnClientClick="return confirm('Overwrite?');" OnClick="btn1_Click" Text="Submit" />
If the users clicks "OK" then the page will post back and you will update the DB. If the user clicks cancel, the page won't postback at all and you won't have to do anything.
Here is your code:-
Add a hidden field in Net(.aspx) page
<form id="form10" runat="server">
<asp:HiddenField ID="hdnField" runat="server" Value="false" />
</form>
The hidden field should be added under Form Tag.The value of this hidden field is initially "false".
Here is what you need to do in Code Behind file (.cs file)
protected void btnSubmits_Click(object sender, EventArgs e)
{
if (hdnField.Value == "false")
{
AddJavascriptCode(itemValue);
}
else if (hdnField.Value == "true")
{
lblMsg.Text = string.Format("You have entered {0}", itemValue);
hdnField.Value = "false";
}
}
Here is the code to capture the response from OK/Confirm or Cancel button.
private void AddJavascriptCode(string itemValue)
{
string script = #"<script language=""JavaScript"" type=""text/javascript"">
window.onload=function()
{
var IsConfirm = 1;
objField = document.getElementById('" + hdnField.ClientID + #"');
objSubmit = document.getElementById('" + btnSubmit.ClientID + #"');
IsConfirm = newConfirm('Test','You have entered " + itemValue + #" value. Do you want to overwrite ?',1,1,0);
if(IsConfirm == true)
{
objField.value = 'true';
objSubmit.click();
}
else
{
objField.value = 'false';
}
}
function newConfirm(title,mess,icon,defbut,mods)
{
if (document.all)
{
retVal = confirm(mess);
retVal = (retVal==1)
}
else
{
retVal = confirm(mess);
}
return retVal;
}
</script>";
Page.ClientScript.RegisterStartupScript(this.GetType(), "Test", script);
}
}
Hope this helps you :).

Categories

Resources