<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 am writing an AJAX function in ASP.Net MVC5 and I am getting a problem that the form AJAX request goes only one time. It is a search page. After I choose the filter I press search I get the correct result. However if I changed the filter and click the search submit again, nothing will happen.
var ajaxFormSubmit = function() {
var $form = $(this);
var options = {
url: $form.attr("action"),
type: $form.attr("method"),
data: $form.serialize()
};
$.ajax(options).done(function (data) {
var target = $($form.attr("data-enbw-target"));
target.replaceWith(data);
debugger;
});
return false;
};
$("form[data-enbw-ajax='true']").submit(ajaxFormSubmit);
<form method="get" id="documentForm" action="#Url.Action("Index", "DocumentSearch")" def data-enbw-ajax="true" data-enbw-target="#documentSearchResult">
<button type="submit" id="submitbtn" name="submitbtn" tabindex="100" class="k-button">
<img src="~/Content/search_small_icon.png" />
#WebResources.DocumentSearchButton
</button>
</form>
#Html.Partial("Results", #Model)
public ActionResult Index(DocumentSearchInput model)
{
if (Request.IsAjaxRequest())
{
return PartialView("Results", result);
}
return View(result);
}
I do not get any error. and when I get a debugger; in javascript. the new data is correct. can you please help me.
You are replacing the form in your ajax success. As such, the new form will not have the submit binding on it. If you truely want to do this you will have to rebind to the new form, or possibly use a delegate instead.
$('parentSelector').on('event', 'childSelector', function(){});
parentSelector - A parent element of the child that pre-exists the child element and should typically not be removed/created during the page lifespan.
childSelector - A selector for the element that will be created/changed/removed at some point in the lifespan of the page.
I found the answer.
the problem wasn't with the submit. the problem was with re-writing the data.
$.ajax(options).done(function (data) {
$("#documentSearchResult").empty();
$("#documentSearchResult").html(data);
});
simply, I empty the div then write inside.
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
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 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.