<body>
<asp:Repeater ID="ProductView" runat="server">
<ItemTemplate>
<asp:Label ID="lblOrderId" runat="server" Text='<%# Eval("OrderId") %>' />
<asp:LinkButton ID="bbtnDelete" CssClass="MordersButton" runat="server" UseSubmitBehavior="false" Text='<%#Eval("PaymentStatus") %>'></asp:LinkButton>
<asp:Button ID="btnDelete" runat="server" Text="Delete" OnClick="DeleteRecord" UseSubmitBehavior="false" />
</ItemTemplate>
</asp:Repeater>
<div id="dialog" style="display: none" align="center">
Do you want to delete this record?
</div>
<script type="text/javascript">
$(function () {
$("[id*=btnDelete]").removeAttr("onclick");
$("#dialog").dialog({
modal: true,
autoOpen: false,
title: "Confirmation",
width: 350,
height: 160,
buttons: [
{
id: "Yes",
text: "Yes",
click: function () {
$("[id*=btnDelete]").attr("rel", "delete");
$("[id*=btnDelete]").click();
}
},
{
id: "No",
text: "No",
click: function () {
$(this).dialog('close');
}
}
]
});
$("[id*=btnDelete]").click(function () {
if ($(this).attr("rel") != "delete") {
$('#dialog').dialog('open');
return false;
} else {
__doPostBack(this.name, '');
}
});
});
</script>
</body>
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
FlavorImage1Bind();
}
}
protected void DeleteRecord(object sender, EventArgs e)
{
RepeaterItem item = (sender as Button).Parent as RepeaterItem;
int addressID = int.Parse((item.FindControl("lblOrderId") as Label).Text);
ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('Record Deleted.')", true);
}
private void FlavorImage1Bind()
{
SqlCommand cmd = new SqlCommand("DC_ManageOrders_Select", cn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#Userid", "1");
cmd.Parameters.AddWithValue("#FilterType", "3");
SqlDataAdapter DA = new SqlDataAdapter(cmd);
DA.Fill(dt);
// dt = sliderhelper.GetsliderImage();
ProductView.DataSource = dt;
ProductView.DataBind();
}
In the repeater control the orderid starts with 1080,
each control has a delete button, I clicked orderid 2031 delete button and in the confirmation dialog box clicked yes.
Once clicked yes the deleted statement gets fired with the orderid 1080 (actually I need to delete the orderid 2031)
Can someone please help to solve this?
Ok, a few things.
First - your title? This is not JUST JavaScript.
You are using jQuery - it should be tagged as such.
You are ALSO using jQuery.UI - it should be tagged as such.
and specific, out of hte jQuery.UI library, you are using the jQuery.UI dialog
Ok, now that been cleared up?
Next up?
I been coding for a long time. As a result, code WHEN possible should avoid things like document.onReady.
And we should try and avoid say having jQuery kind of, sort of, perhaps attach some click event to some button in some magic way. Now, don't get me wrong, document reedy, and magic jQuery selector functions that just run all by themselves like magic? Not too bad, but those that kind of pick out some control and THEN add some click stuff? I telling you now, REALLY make a effort to avoid such code.
This is also why I don't use the bootstrap dialogs. I think they look great, but you specify a bunch of classes - and some how, and somewhere by some feat of magic that makes a dialog pop up? (wow - just TRY to debug that kind of mess). I love bootstrap, but I quite much settled on the jQuery.UI dialog - and now I can write code that humans can read, but MORE important humans can also follow.
Now the key point here? (when we can avoid that fancy footwork, do so! - so this is not always! - but at least try!!!).
So, when building code? We place a button on the form. We have that button when clicked on run some code. And as noted, we should have a simple define of that function to run, and setup that information AT that location, and button in code. The result is code all of a sudden becomes enjoyable and fun again. It also means that you drop in a button, specify the functions to run (client side, and server side). And then you are quite much done.
Ok, next up:
in asp.net, when you use the onClientClick() event, you can VERY nice control if the server button code is to run, or not.
If the js function returns true, then your server side button click code will run (code behind).
And if the js function returns false, then your server side button click code will NOT run.
So, this means we simply want to specify a simple function for that button click, and ALSO a OnClientClick() event is also specified.
That function will return true/false, and that's quite much all we need to do.
Now, of course these days, jQuery.UI (and most new web widgets are async and they don't wait. However, that will not matter here.
so, say markup is this:
<asp:Button ID="btnDelete" runat="server" Text="Delete"
OnClick="DeleteRecord" UseSubmitBehavior="false"
OnClientClick = "return mydeleteprompt(this)" />
The above is ALL you need.
So, if the js function mydeleteprompt returns true, then the server side code you have will run
And VERY NICE that you using the btn.parent trick to get the repeater row - GREAT on your part!!! This is a great idea, and then you just drop in a button, use btn.Parent, and you can then just 100% ignore the repeater event model, and just code as if you dropped any old button on the form, and then attached a server side code behind event.
Love that trick/idea you using. Well done!!!
Ok, so, now lets build that js function - have it pop the jQuery dialog.
<script>
mydelpromptok = false
function mydelprompt(btn) {
if (mydelpromptok) {
return true
}
var myDialog = $("#mydelprompt")
myDialog.dialog({
title: "Confirm delete",
modal: true,
width: "320px",
resizable: false,
appendTo: "form",
autoOpen: false,
buttons: {
ok: function () {
myDialog.dialog("close")
mydelpromptok = true
btn.click()
},
cancel: function () {
myDialog.dialog("close")
}
}
})
myDialog.dialog('open')
return false
}
Note the "trick" here. Since jQuery.UI dialogs do NOT wait, then when you click on that standard asp.net button, the above dialog js routine runs. It will pop the dialog, and of course return false (so the server side code don't run/trigger).
Now, the dialog is displayed. Either you hit the ok button in dialog, or the cancel. Well, for cancel, we just close the dialog - nothing will happen.
But, if we hit Ok? Then we set our flag = true, and simply click the the SAME button again!!!! now the code will call this routine again, but this time, our flag = true, and thus the server side code will run.
So my "fake" coding standard is
function name = mycool()
and thus my flag for such functions will by mycoolok (I add the word "ok" to that function as a simple true/false flag.
But anyway, whatever you like - the trick here is that flag, and thus we save a hairy cat ball of code.
Enjoy:
Edit: ---------------------
Ok, so lets try this without a repeater. Lets do a proof of concept, and ensure that a simple button on a form, and a jQuery.UI dialog works.
So, we drop in a button, a cute "div" that will be the dialog, and then our js code to pop this dialog.
if we answer "ok", then the server side button code will run, if we don't ok /confirm the dialog, we will NOT run the server side code.
So, we have this markup:
<asp:Button ID="cmdDelete" runat="server" Height="30px"
OnClick="Button1_Click" Text="Dialg test" Width="130px"
OnClientClick="return mydialog(this)" ClientIDMode="Static"/>
<div id="MyFunDialog" style="display:none">
<h2>Really do the button click?</h2>
<h3>Ok = run server buttion</h3>
<h3>cancel - don't run button code</h3>
</div>
<script>
myokok = false
function mydialog(btn) {
if (myokok) {
return true
}
// lets pop jquery.UI dialog
var mydiv = $("#MyFunDialog")
mydiv.dialog({
modal: true, appendTo : "form",
title: "Really do this?", closeText : "",
width: "400px",
buttons: {
' ok ': function () {
mydiv.dialog('close')
myokok = true
btn.click() // click button again
},
' cancel ': function () {
mydiv.dialog('close')
}
}
});
return false
}
</script>
And then we click on the button - lets wire up the server side (code behind) for this example. Our button code will thus be this:
protected void Button1_Click(object sender, EventArgs e)
{
Response.Write("<h2>This is the server button click</h2>");
}
ok, now when we run this test simple example? you get this:
So, get the above working. Start blank page - test that you have jQuery.UI installed and working.
once you get the above working, then you can use the approach in your application over and over - it is a GREAT design pattern.
Now ONLY when you are able to get the above working?
Ok, then, lets try this with a repeater, and see how it works much the same.
--------- repeater example ----------------
Now, as noted, if you do this inside of a repeater ? It quite much the same.
With a repeater, we would have say this:
<asp:Repeater ID="Repeater1" runat="server">
<ItemTemplate>
<div style="border-style:solid;color:black;width:300px;float:left">
<div style="padding:5px;text-align:right">
Hotel Name: <asp:TextBox ID="txtHotelName" runat="server" Text ='<%# Eval("HotelName") %>' Width="150px" />
<br />
First Name: <asp:TextBox ID="txtFirst" runat="server" Text ='<%# Eval("FirstName") %>' Width="150px" />
<br />
Last Name: <asp:TextBox ID="txtLast" runat="server" Text ='<%# Eval("LastName") %>' Width="150px" />
<br />
City: <asp:TextBox ID="txtCity" runat="server" Text ='<%# Eval("City") %>' Width="150px" />
<br />
Active: <asp:CheckBox ID="chkActive" runat="server" Checked = '<%# Eval("Active") %>'/>
<asp:HiddenField ID="PK" runat="server" Value = '<%# Eval("ID") %>'/>
<asp:Button ID="cmdDelete" runat="server" Text="Delete" style="margin-left:20px"
OnClientClick="return mydelprompt(this)"
OnClick="cmdDelete_Click"/>
</div>
</div>
<div style="clear:both;height:4px"></div>
</ItemTemplate>
</asp:Repeater>
</div>
<div id="mycoolconfirmdialog" style="display:none">
<h2>About to delete hotel</h2>
<h3>This cannot be un-done</h3>
</div>
<script>
myokok = false
function mydelprompt(btn) {
if (myokok) {
return true
}
// lets pop jquery.UI dialog
var mydiv = $("#mycoolconfirmdialog")
mydiv.dialog({
modal: true, appendTo : "form",
title: "Confirm delete of Hotel", closeText : "",
width: "400px",
buttons: {
' ok ': function () {
mydiv.dialog('close')
myokok = true
btn.click() // click button again
},
' cancel ': function () {
mydiv.dialog('close')
}
}
});
return false
}
</script>
And our code to load this looks like this:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
LoadData();
}
}
public void LoadData()
{
using (SqlCommand cmdSQL = new SqlCommand("SELECT * FROM tblHotels ORDER by HotelName",
new SqlConnection(Properties.Settings.Default.TEST4)))
{
cmdSQL.Connection.Open();
Repeater1.DataSource = cmdSQL.ExecuteReader();
Repeater1.DataBind();
}
}
And now lets add (fill out) the delete button code:
protected void cmdDelete_Click(object sender, EventArgs e)
{
// delete the row from database
Button btn = (Button)sender;
RepeaterItem gRow = (RepeaterItem)btn.Parent;
string PK = ((HiddenField)(gRow.FindControl("PK"))).Value;
using (SqlCommand cmdSQL = new SqlCommand("DELETE FROM tblHotels WHERE ID = #ID",
new SqlConnection(Properties.Settings.Default.TEST4)))
{
cmdSQL.Parameters.Add("#ID", SqlDbType.Int).Value = PK;
cmdSQL.Connection.Open();
cmdSQL.ExecuteNonQuery();
}
LoadData(); // re-load repeater
}
note very careful - we had to add a hidden field to hold the database PK "id". If you are concerned about security and don't want the PK id to be existing in the client browser side? Then dump the Repeater, and use a ListView. They work VERY similar - almost identical, but ListView (and grid views) have DataKeys option to hold the PK - and thus you do NOT have to put the PK in the markup, or expose it to client side.
Regardless, the results now look like this:
Try changing this.name in the line where you do __doPostBack to
__doPostBack(this.id, '');
You are sending the name of the button which would be the same for each of the items in the repeater, the id is unique. It may be the reason why the first item is the one that is deleted.
my asp project has a asp button which named 'Save'. However, i need to change it to 'Update' in jQuery to do other thing in one button.
The problem is the C# onclick code is still read it as Save..
Code:
//Main
<asp:Button ID="btnSubmit" runat="server" Text="Save" />
//JQuery
$("#<%=btnSubmit.ClientID %>").val("Update");
//C#
var button = sender as Button;
var buttonName = button.Text; //Save
Update1
Question is:
I need to change the button name in JQuery
$("#<%=btnChangeName.ClientID %>").click({
$("#<%=btnSubmit.ClientID %>").val("Update"); //Change Save to Update
});
Then use it in C#:
protected void btnSubmit_Click(object sender, EventArgs e)
{
var button = sender as Button;
var buttonName = button.Text;
if (buttonName == "Save")
{//something}
else
{//something}
}
if you want to change the Name to Update1 in Jquery
try like this
$("#<%=btnSubmit.ClientID%>").val('Update');
Event you neeed to use is OnClientClick
Usage example
OnClientClick="onupd();return false;"
Update
Decalre a Hidden FIeld
<asp:HiddenField runat="server" ID="hdntest" Value="0" />
assign the button change value to update and assign it to the hidden field
not access that hidden value in your code behind.
you can assign Button value to Hidden Field like this
$("#<%=btnSubmit.ClientID %>").val("Update");
$("#<%=hdntest.ClientID%>").val($("#<%=btnSubmit.ClientID%>").attr("value"));
If you change the Button.Click value, then it will move to a different method onClick;
private void Form1_Load(object sender, EventArgs e)
{
Button b = new Button();
b.Name = "btnSubmit";// creating here for intellisense - you would create on your front-end
bool recordExists = true;
Button b1 = Controls.Find("btnSubmit", true)[0] as Button;
//the above is for winforms - you'd have to change for web form
b1.Text = recordExists ? "Update" : "Save";
b1.Click += doUpdateOrSave;
}
protected void doUpdateOrSave(object sender, EventArgs e)
{
Button b = sender as Button;
if (b.Text == "Save")
{
//save
}else
{
//update
}
}
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
I have a button with OnClick event on my web page.
<asp:TextBox ID="tbMailID" runat="server" Width="250px"></asp:TextBox>
<asp:Button ID="btnSubmit" runat="server" OnClick="btnSubmit_Click" Text="Submit" />
C# code:
protected void btnSubmit_Click(object sender, EventArgs e)
{
bool IsGmail = CheckMailId(tbMailID.Text);
if(!IsGmail)
{
string strScript = "confirm('Mail id is not from gmail, do you still want to continue?');";
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "strScript", strScript, true);
}
SendMail();
}
The page accepts a mail id in textbox and on submit sends a mail.
But if mail-id is not an gmail id (validated by CheckMailId) i want to show a confirmation box to user whether he/she wants to get a mail, based on the Yes/No clicked.
But the javascript will get call after the submit event is served and mail is sent.
if i add a return SendMail() will never get calls
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "strScript", strScript, true);
return;
What could be a possible solution here?
Note: the code posted is simplified version of my real use case.
CheckMailId - is just a name to show, it calls up many other functions and do few db process. So incorporating that in javascript, i would like to avoid.
You can call a script befroe event lke this:-
<script type="text/javascript">
function Confirm() {
var yourstring = document.getElementById('<%= tbMailID.ClientID %>').value;
if (/#gmail\.com$/.test(yourstring)) {
return true;
}
else
{
if (confirm("Mail id is not from gmail, do you still want to continue?") == true)
return true;
else
return false;
}
}
</script>
strong text
<asp:Button ID="btnSubmit" runat="server" OnClientClick="return Confirm();" OnClick="btnSubmit_Click" Text="Submit" />
I'm trying to set a button's enable/disable based on a checkbox being checked or not. Below is my javascript and asp code, which doesn't work. I am not sure if the function is not called at all, or something is wrong with how I disable the button.
<script type="text/javascript">
function OnChkAgreeChanged(chkAgree) {
if (document.getElementById"chkAgree").checked)
document.getElementById("btnSubmit").SetEnabled(true);
else
document.getElementById("btnSubmit").SetEnabled(false);
}
</script>
<asp:checkbox ID="chkAgree" runat="server"
Text="blablabla" onchange="javascript:OnChkAgreeChanged(this);"/>
<dx:ASPxButton ID="btnSubmit" runat="server" Text="Submit"
UseSubmitBehavior="true" AutoPostBack="true" Width="175px"
CssClass="submitButton" OnClick="btnSubmit_Click" enabled="false">
</dx:ASPxButton>
DevExpress creates a client instance object for each one of it's various controls. In this case it will create an ASPxClientButton for btnSubmit. Since you haven't given btnSubmit a ClientInstanceName, you can access it like so:
window.aspxGetControlCollection().elements['<%= btnSubmit.ClientID %>'];
That means your entire handler function could look something like this:
function OnChkAgreeChanged(chkAgree)
{
btnSubmit = window.aspxGetControlCollection().elements['<%= btnSubmit.ClientID %>'];
if(!(btnSubmit === null || btnSubmit === undefined)) { btnSubmit.SetEnabed(chkAgree.checked); }
}
You could also make your life easier by defining the ClientInstanceName attribute like so:
<dx:ASPxButton ID="btnSubmit" ClientInstanceName="btnSubmit" runat="server" Text="Submit"
UseSubmitBehavior="true" AutoPostBack="true" Width="175px"
CssClass="submitButton" OnClick="btnSubmit_Click" enabled="false">
</dx:ASPxButton>
Then, you'd be able to use that directly in your handler:
function OnChkAgreeChanged(chkAgree)
{
if(!(btnSubmit === null || btnSubmit === undefined)) { btnSubmit.SetEnabed(chkAgree.checked); }
}
You'll note that I like to check if that thing is null or not because if you set the display to none in the Code-Behind or otherwise disable it, it's very likely the DevExpress magic/voodoo (pick one) won't emit the JS creating that instance object.
chkAgree is an object not a string. You don't have to use document.getElementById. Try this...
<script type="text/javascript">
function OnChkAgreeChanged(chkAgree) {
if (chkAgree.checked)
document.getElementById("btnSubmit").disabled = null;
else
document.getElementById("btnSubmit").disabled = true;
}
</script>
Also, in onchange="javascript:OnChkAgreeChanged(this);" javascript: may not be required. Pls check ASP documentation.
JQuery Solution
$(document).ready(function () {
$('#chkAgree').click(function () {
if (this.checked) {
$("#btnSubmit").prop('disabled', false);
}
else {
$("#btnSubmit").prop('disabled', true);
}
});
});
Or if you want to do same thing using JavaScript can use solution suggested by mohkhan.
Use the ClientInstanceName and ClientEnabled (not the Enabled) properties for this purpose:
function OnChkAgreeChanged(chkAgree) {
var checked = chkAgree.checked;
btnSubmit.SetEnabled(checked);
}
</script>
<asp:checkbox ID="chkAgree" runat="server" Text="blablabla" onchange="OnChkAgreeChanged(this);"/>
<dx:ASPxButton ... ClientInstanceName="btnSubmit" ClientEnabled="False">
</dx:ASPxButton>