how to capture javascript var value into asp.net page - javascript

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 :).

Related

Javascript Confirm not Stopping request from post back if pressed cancel?

I am using Javascript function with confirm() message box and also having RequiredFieldValidator if I press cancel on my confirm message box but ValidatorGroup is true then it not stopping a request from getting post back.
I want to implement in such a way that If validatorGroup is treu but function return false then request should not get post back
Here is my Code:-
<asp:Button ID="btnStaffSendRequest" runat="server" Text="Send" OnClientClick="UploadRefrrel()"
UseSubmitBehavior="false" ValidationGroup="SaveRequestGroup" OnClick="btnStaffSendRequest_OnClick"
TabIndex="1000" />
Here is my Javascript Function:-
<script language="javascript" type="text/javascript">
function UploadRefrrel() {
var hiddenFile = this.document.getElementById("<%= hfInputForm.ClientID %>");
var upload = $find("<%= radUploadFiles.ClientID %>");
var inputs = upload.getUploadedFiles();
var retVal;
if (hiddenFile != null && hiddenFile.value != "" && inputs.length == 0) {
retVal = confirm("FYI - Only 'Referral Form' is attached. Do you want to proceed without any other attachment?");
}
return retVal;
}
</script>
<asp:CustomValidator ID="validatePostBack" runat="server" Display="None" ClientValidationFunction="Validate_PostBack"
ValidationGroup="SaveRequestGroup" ErrorMessage="<br /> Please add other attachment."></asp:CustomValidator>
<telerik:RadScriptBlock ID="uploadReferel" runat="server">
<script language="javascript" type="text/javascript">
function Validate_PostBack(sender, e) {
var hiddenFile = this.document.getElementById("<%= hfInputForm.ClientID %>");
var upload = $find("<%= radUploadFiles.ClientID %>");
var inputs = upload.getUploadedFiles();
if (hiddenFile != null && hiddenFile.value != "" && inputs.length == 0) {
var retVal = confirm("FYI - Only 'Referral Form' is attached. Do you want to proceed without any other attachment?");
if (retVal == true) {
e.IsValid = true;
}
else {
e.IsValid = false;
}
}
}
</script>
</telerik:RadScriptBlock>
Found my solution and working fine

Javascript Function Not Firing from C# Function ASP.Net

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.

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;
}
}

User Control with Client + Server Side CustomValidation; Wrong Client side validator is picked

I have a user control which contains a CustomValidator which is used according to whether a RadioButton is checked or not (there are several RadioButtons, I'm only showing the relevant one)
<asp:RadioButton runat="Server" ID="RadioBetween" GroupName="DateGroup" CssClass="date_group_options_control_radio" />
<asp:TextBox ID="FromDate" runat="server" Columns="8"></asp:TextBox>
<asp:TextBox ID="ToDate" runat="server" Columns="8"></asp:TextBox>
<asp:CustomValidator ID="DateValidator" runat="server" Display="Dynamic" ClientValidationFunction="ValidateDateFields_Client" OnServerValidate="ValidateDateFields"></asp:CustomValidator>
There is some client + server side validation code (the server side code does exactly the same thing and is skipped for brevity)
<script type="text/javascript">
function ValidateDateFields_Client(source, args)
{
if ("<%=EnableValidation%>" == "True")
{
var bRadioBetweenSelected = false;
var oRadio = document.getElementById('<%=RadioBetween.ClientID%>');
if (oRadio != null && (oRadio.checked == true || oRadio["checked"] == true))
{
bRadioBetweenSelected = true;
}
if (bRadioBetweenSelected)
{
var oFromDate = document.getElementById('<%=FromDate.ClientID%>');
var oToDate = document.getElementById('<%=ToDate.ClientID%>');
if (oFromDate != null && oToDate != null)
{
var sFromDate = oFromDate.value;
var sToDate = oToDate.value;
source.innerHTML = ValidateFromToDate(sFromDate, sToDate, args);
if (!args.IsValid)
{
return;
}
}
else
{
args.IsValid = true;
}
}
else
{
args.IsValid = true;
}
}
}
</script>
There are two instances of this control in the page. When running the client side version it hits the wrong one (the version of the control which is disabled). You can see from the generated HTML both are correctly specified. I'm not sure how .NET works out which clientside function to call given they both have the same name.
<script type="text/javascript">
//<![CDATA[
var ctl00_MCPH1_QueryTextValidator = document.all ? document.all["ctl00_MCPH1_QueryTextValidator"] : document.getElementById("ctl00_MCPH1_QueryTextValidator");
ctl00_MCPH1_QueryTextValidator.controltovalidate = "ctl00_MCPH1_SearchTextBox";
ctl00_MCPH1_QueryTextValidator.focusOnError = "t";
ctl00_MCPH1_QueryTextValidator.display = "Dynamic";
ctl00_MCPH1_QueryTextValidator.evaluationfunction = "CustomValidatorEvaluateIsValid";
ctl00_MCPH1_QueryTextValidator.clientvalidationfunction = "ValidateQueryText_Client";
ctl00_MCPH1_QueryTextValidator.validateemptytext = "true";
var ctl00_MCPH1_DisplayOptionsControl1_DateValidator = document.all ? document.all["ctl00_MCPH1_DisplayOptionsControl1_DateValidator"] : document.getElementById("ctl00_MCPH1_DisplayOptionsControl1_DateValidator");
ctl00_MCPH1_DisplayOptionsControl1_DateValidator.display = "Dynamic";
ctl00_MCPH1_DisplayOptionsControl1_DateValidator.evaluationfunction = "CustomValidatorEvaluateIsValid";
ctl00_MCPH1_DisplayOptionsControl1_DateValidator.clientvalidationfunction = "ValidateDateFields_Client";
var ctl00_MCPH1_PreferencesControl1_PreferencesTabContainer_DisplayOptionsTab_DisplayOptionsControl_DateValidator = document.all ? document.all["ctl00_MCPH1_PreferencesControl1_PreferencesTabContainer_DisplayOptionsTab_DisplayOptionsControl_DateValidator"] : document.getElementById("ctl00_MCPH1_PreferencesControl1_PreferencesTabContainer_DisplayOptionsTab_DisplayOptionsControl_DateValidator");
ctl00_MCPH1_PreferencesControl1_PreferencesTabContainer_DisplayOptionsTab_DisplayOptionsControl_DateValidator.display = "Dynamic";
ctl00_MCPH1_PreferencesControl1_PreferencesTabContainer_DisplayOptionsTab_DisplayOptionsControl_DateValidator.evaluationfunction = "CustomValidatorEvaluateIsValid";
ctl00_MCPH1_PreferencesControl1_PreferencesTabContainer_DisplayOptionsTab_DisplayOptionsControl_DateValidator.clientvalidationfunction = "ValidateDateFields_Client";
//]]>
</script>
Do i need to add something in to scope it? What's the best way to achieve this? If I disable the loading of the second control everything works fine.
Your client validation function is generated with the same name for both your user controls. There will be two ValidateDateFields_Client() functions in your page, and of course the interpreter will only call one of them.
One way to work around that problem would be to generate unique function names:
<script type="text/javascript">
function ValidateDateFields_Client_<%=RadioBetween.ClientID%>(source, args)
{
// ...
}
</script>
<asp:CustomValidator ID="DateValidator" runat="server" Display="Dynamic"
ClientValidationFunction="ValidateDateFields_Client_"
OnServerValidate="ValidateDateFields"></asp:CustomValidator>
protected void Page_PreRender(object sender, EventArgs e)
{
DateValidator.ClientValidationFunction += RadioBetween.ClientID;
}

Categories

Resources