<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.
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'm trying to disable the two list boxes on load of my web form, but the list boxes are not disabling. I tried the code below but it's still not working on my case. Please let me know where I'm going wrong.
DESIGNER CODE
<telerik:RadListBox ID="lbSelectedDepartmentContacts" runat="server" Width="220px" AutoPostBackOnTransfer="true" AutoPostBackOnReorder="true" AutoPostBackOnDelete="true" CheckBoxes="false" AllowTransfer="true" AllowTransferOnDoubleClick="true" TransferToID="lbDepartmentContacts"
Height="276px" SelectionMode="Single" AllowReorder="True">
<ButtonSettings ShowTransfer="false" ShowTransferAll="false" ReorderButtons="Common" ShowReorder="true" />
</telerik:RadListBox>
</td>
</tr>
<tr>
<td align="right">
<telerik:RadListBox ID="lbDepartmentContacts" runat="server" Width="200px" CheckBoxes="false" AutoPostBackOnTransfer="true" AllowTransfer="true" AllowTransferOnDoubleClick="true" TransferToID="lbSelectedDepartmentContacts"
Height="250px" SelectionMode="Single">
<ButtonSettings TransferButtons="Common" ShowTransfer="false" ShowTransferAll="false" />
</telerik:RadListBox>
BACKCODE
public void DisableControls()
{
System.Text.StringBuilder sb = new System.Text.StringBuilder();
sb.Append(#"<script language='javascript'>function DisableControls(){");
sb.Append(#"var lbl = document.getElementById('lbSelectedDepartmentContacts').disabled = true;");
sb.Append(#" var Txt = document.getElementById('txtDepartmentCategoryContactsFilter').disabled = true;");
sb.Append(#" var btn = document.getElementById('RadButton1').disabled = true;");
sb.Append("}</script>");
if (!ClientScript.IsClientScriptBlockRegistered("JSScriptBlock"))
{
ClientScript.RegisterClientScriptBlock(this.GetType(), "JSScriptBlock",
sb.ToString());
}
string funcCall = "<script language='javascript'>DisableControls();</script>";
if (!ClientScript.IsStartupScriptRegistered("JSScript"))
{
ClientScript.RegisterStartupScript(this.GetType(), "JSScript", funcCall);
}
}
Tried Also:
Page.ClientScript.RegisterStartupScript(this.GetType(), "text", "DepartmentLoad();", true);
JAVASCRIPT CODE
function DepartmentLoad(){
document.getElementById("lbSelectedDepartmentContacts").disabled = true;
document.getElementById("lbDepartmentContacts").disabled = true;
document.getElementById("txtDepartmentCategoryContactsFilter").disabled = true;
ducument.getElementById("RadButton1").disabled = true;}
C# only approach to disable your 2 listboxes...
Delete or comment out your existing DisableControls() method then add the following...
protected void Page_Load(object sender, EventArgs e)
{
if (Page.IsPostBack) return;
DisableControls();
}
private void DisableControls()
{
lbSelectedDepartmentContacts.Enabled = lbDepartmentContacts.Enabled = false;
}
You should generally:
Use Sys.Application.Load to register your script. Calling the function earlier will cause problems with using the client-side API of the IScriptControls: http://msdn.microsoft.com/en-us/library/bb383829.aspx and http://docs.telerik.com/devtools/aspnet-ajax/controls/window/troubleshooting/executing-javascript-code-from-server.
use the API the Telerik control provides: http://docs.telerik.com/devtools/aspnet-ajax/controls/listbox/client-side-programming/objects/radlistbox-object.
There seems to be no set_enabled() or set_disabled() method on the client (at least at the time of writing), so this seems to be impossible with JS, so you should go with the other answer that tells you to use server code.
I am using textbox for searching items from data base and loading them in gridview and
i used custom paging on gridview to show only 25 records per page
and i found java script for searching records on client side as
script>
function filter2(phrase, _id) {
var words = phrase.value.toLowerCase().split(" ");
var table = document.getElementById(_id);
var ele;
for (var r = 1; r < table.rows.length; r++) {
ele = table.rows[r].innerHTML.replace(/<[^>]+>/g, "");
var displayStyle = 'none';
for (var i = 0; i < words.length; i++) {
if (ele.toLowerCase().indexOf(words[i]) >= 0)
displayStyle = '';
else {
displayStyle = 'none';
break;
}
}
table.rows[r].style.display = displayStyle;
}
}
</script>
and calling this as:
<input name="txtTerm" onkeyup="filter2(this, '<%=GridView1.ClientID %>')" placeholder="Search" type="text"/>
this function search record from activated page and obviously searching from whole database will be done on server side and i used asp textbox
but i need onkeyup="filter2(this, '<%=GridView1.ClientID %>')"event in my asp textbox e-g
<asp:TextBox ID="txtSearch" onkeyup="filter2(this, '<%=GridView1.ClientID %>')" placeholder="Search" runat="server" AutoPostBack="True" OnTextChanged="txtSearch_TextChanged" />
but asp didn't allow me to do that..
i need your help to achieve this.
thanks in advance.
EDIT:
I need both searching (client side, server side) in single textbox
because
client side allow searching from loaded page of gridview and
server side allow searching from database on clicking
You could add the client attribute of rendered input control via code behind:
protected void Page_Load(object sender, EventArgs e)
{
txtSearch.Attributes.Add("onkeyup", string.Format("filter2(this,'{0}')",GridView1.ClientID)");
}
EDIT:
After the right comment of #Lukas, we should say that the main problem was the use of <%=GridView1.ClientID %> inline expression inside the textbox webcontrol:
<%= %> will write the string directly to the response-stream, which happens after the server control is constructed, so will be rendered as string and not resolved.
For example:
<asp:Label runat="server" ID="label">test</asp:Label>
<asp:TextBox runat="server" ID="txt" Text="<%# label.ID %>" onkeyup="alert('<%: label.ID %>')"></asp:TextBox>
This is what we have in output:
I have asp:LinkButton, input Button defined as:
<asp:LinkButton ID="lnkViewPdf" runat="server" CssClass="icoMiniTest" ClientIDMode="Static" >View Office Pdf</asp:LinkButton>
<input id="Button2" type="button" value="TestEnable" onclick="TestEnable(document.getElementById('lnkViewPdf'));" />
the LinkButton is initially disabled in code-behind as:
if (!IsPostBack)
{
this.lnkViewPdf.Enabled = false;
}
and needs to be enabled when Button2 is clicked, so I am calling javascript function to enable the link as:
function TestEnable(lnkbutton) {
alert('TestEnable() called');
alert(lnkbutton.id);
lnkbutton.disabled = "";
//$("#lnkbutton").removeAttr('disabled'); //even this doesn't work
}
But I am not able to enable the linkbutton.
Am I missing something?
Thank you!
__________________________________________________
Anyone interested in solution to above problem:
In code-behind:
this.lnkViewPdf.Attributes["disabled"] = "disabled";
this.lnkViewPdf.Attributes["onclick "] = "return false";
.js:
function TestEnable(lnkbutton) {
$(lnkbutton).removeAttr('disabled');
lnkbutton.onclick = "";
}
NOTE: When setting lnkViewPdf.Enabled = false; LinkButton was being rendered as
<a id="lnkViewPdf" class="aspNetDisabled icoMiniTest">View Office Pdf</a>
see the style class aspNetDisabled, something added by ASP.Net
However setting disabled/onclick attributes from the codebehind as shown above, render Linkbutton as:
<a id="lnkViewPdf" class="icoMiniTest" disabled="disabled" onclick ="return false" href="javascript:__doPostBack('lnkViewPdf','')">View Office Pdf</a>
HTH.
Try now...
function TestEnable(lnkbutton) {
lnkbutton.disabled = "";
lnkbutton.onclick = "";
}
In the code behind, rather than disable by setting Enabled = false, set:
lnkViewPdf.Attributes["disabled"] = "disabled"
So your javascript function:
function TestEnable(lnkbutton) {
alert('TestEnable() called');
alert(lnkbutton.id);
lnkbutton.disabled = "";
}
Your markup:
<asp:LinkButton ID="lnkViewPdf" runat="server" CssClass="icoMiniTest" ClientIDMode="Static" >View Office Pdf</asp:LinkButton>
<input id="Button2" type="button" value="TestEnable" onclick="TestEnable(document.getElementById('<%= lnkViewPdf.ClientID %>')); return false;" />
And your code-behind:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
lnkViewPdf.Attributes["disabled"] = "disabled";
}
$("#<%=lnkViewPdf.ClientID %>").removeAttr("disabled");
You need to know the .Net constructed name in order to accomplish it. The easiest way is to have it set in the head of the page if you can:
<script language="javascript">
var lnkbuttonToEnableId = "<%= this.lnkViewPdf.ClientId %>";
function TestEnable() {
alert('TestEnable() called');
lnkbuttonToEnableId.disabled = false;
}
</script>
At any rate, the only way to get it to work is to pass the ClientId of lnkViewPdf to the function somehow.
try both of those:
<input id="Button2" type="button" value="TestEnable"
onclick="TestEnable(document.getElementById('<%= lnkViewPdf.ClientID %>'));" />
or
$("#<%= lnkViewPdf.ClientID %>").removeAttr('disabled');
UPDATE: Since you are disabling the LinkButton on server side .NET strips the href attribute from the <a> html element. What you should do to prevent the lost of that information is to disable the LinkButton on the client and then enable it when you need to. Also instead of disabling it all you need to do is remove the href attribute.
So first you need to retain the href and remove it so the <a> link become disabled:
$(document).ready(function () {
var $lnkViewPdf = $("#lnkViewPdf");
$lnkViewPdf.data("href", $lnkViewPdf.attr("href"));
$lnkViewPdf.removeAttr("href");
});
and the function that enables it:
function TestEnable(lnkViewPdfId) {
var $lnkViewPdf = $("#" + lnkViewPdfId);
$lnkViewPdf.attr("href", $lnkViewPdf.data("href"));
}
If you disable the LinkButton using:
if (!IsPostBack)
{
this.lnkViewPdf.Enabled = false;
}
Then the href attibute won't be displayed in the HTML. If you manually add the disabled attribute instead:
if (!IsPostBack)
{
lnkViewPdf.Attributes.Add("disabled", "disabled");
}
Then you're code will work just fine.
Oh!.. and one last thing: You need to set the PostBackUrl property for the LinkButton. You missed it in your example.