ASP.NET- Prompt confirmation only if needed - javascript

I have a button. And I have a Session["actionMode"]. Here what I do in my buttonClick event:
protected void Button1_Click(object sender, EventArgs e)
{
if ((int)Session["actionMode"]==1)
{
//Do something
}
else if ((int)Session["actionMode"]==3)
{
//After confirmation delete a record
}
}
As you can see if value of Session["actionMode"] equals 3 a record is deleted. But before deletion I want to prompt the user to confirm the action. So if value of Session["actionMode"] does not equal 3 I don't need any confirmation because it does not do anything that can't be undone. Is there a way I can achieve this? Javascript maybe?

This code block...
{
//After confirmation delete a record
}
You are executing server side code, and in need for user interaction.
Whatever you do (client or server) you have to split this. A server side alternative.
{
// Display a confirmation including server side controls.
}
protected void YesDeleteTheDamnRecord_Click(object sender, EventArgs e)
{
// Delete it now.
}
And here is one solution with client side interaction.
Check the value of "actionMode" way before displaying Button1.
If it's equal to "3" attach a client side event handler to Button1.OnClientClick.
Display a confirmation (window.confirm maybe)
If user clicks "Yes" execute server side code and delete the record.

I would suggest you to use following approach for deletion.....
protected void Button1_Click(object sender, EventArgs e)
{
if ((int)Session["actionMode"]==1)
{
//Do something
}
else if ((int)Session["actionMode"]==3)
{
//Call Javascript Function which will call Ajax
}
}
Javascript:
function callAjax()
{
if(confirm(do you want to delete data?))
{
call Ajax Page
}
else
{
return;
}
}
Ajax Page:
PageLoad
{
Get Session["actionMode"] Value
Do your Delete here...
}

Related

How to delete a button click event?

In my project, there is a asp button with a C# button_Onclick handler. The problem is when you click the button on html, the event will be kept by browser. For example, the event will be sent if you refresh the browser..
I have tried add a return; to the end of the button_Onclick handler and a JavaScript for thebutton_Onclick handler to call, but all fail.
asp:
<asp:Button ID="btnSubmit" runat="server" Text="Save" />
C#:
protected void btnSubmit_Click(object sender, EventArgs e)
{
.......
return;
}
Assuming your code makes a POST request when clicking the button, this is how browsers behave and should behave on refresh. They must send the submitted data again to the server. If you want to avoid this, then in your submit handler method you should do a redirect to another URL after doing whatever your handler does.
For example if form.asp displays your form, then in your handler you can redirect to form.asp?message=thankyou (notice the different URL), then in case of refresh, your form will not be sent again by the browser to the server.
Also, best would be to use a 303 redirect.
You should redirect to another page to avoid this.But In case if you want to stay on the workaround is as follows.
In your pageload_Event capture the dateTime.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Session["update"]=Server.UrlEncode(System.DateTime.Now.ToString());
}
}
In the Page_PreRender Event Copy the sessionVariable to ViewState Variable.You can refer following to get a clear understanding on Page Life cycle. "http://www.codeproject.com/Articles/667308/ASP-NET-Page-Life-Cycle-Events"
public void Page_PreRender(object obj, EventArgs e)
{
ViewState["update"] = Session["update"];
}
Now in your button on click event compare the ViewState ans session variable.Allow into the block if both the values are equal.
protected void btnSubmit_Click(object sender, EventArgs e)
{
if (Session["update"].ToString() == ViewState["update"].ToString())
{
try
{
-----------Your Logic
}
finally
{
Session["update"]=Server.UrlEncode(System.DateTime.Now.ToString());
}
}
}

How can I respond to the click of a button (without a submission of the page) when I need to run server-side code?

This is sort of a Catch-22 with my ASP.NET (Sharepoint) WebPart/page. I need to respond to a button click, but doing that requires that the code be client-side (jQuery), because server-side/code-behind seems only to be available for the "Submit" process, and I don't want to submit the page in this scenario.
To be more clear, this is what I can do to have a button (an HtmlButton, to be more precise), and respond to clicking it without submitting the form:
Server-side (C#):
HtmlButton btnAddFoapalRow = null;
. . .
btnAddFoapalRow = new HtmlButton();
btnAddFoapalRow.Attributes["type"] = "button";
btnAddFoapalRow.InnerHtml = "+";
btnAddFoapalRow.ID = "btnAddFoapalRow";
this.Controls.Add(btnAddFoapalRow);
Client-side (jQuery):
$(document).on("click", '[id$=btnAddFoapalRow]', function (e) {
... script elided for brevity
});
This works fine.
I can do it all on the server side (in C#) for the "submit" button, like so:
Button btnSave = new Button();
btnSave.Text = "Save";
btnSave.Click += new EventHandler(btnSave_Click);
this.Controls.Add(btnSave);
. . .
private void btnSave_Click(object sender, EventArgs e)
{
. . . code elided for brevity
}
But the crux of the problem is that I need to respond to a button click without submitting the form, but then run some code on the server side. I can fulfill the first requirement in jQuery (as shown above with HtmlButton btnAddFoapalRow), but I need to ultimately call some C# code in response to the click - I need to carry out an action on the server side.
So my question is: How can I, from the client-side code, "poke" the server-side code to "wake up and call this (some) function"?
Maybe I can update a variable (HiddenField) that I create in C# like so:
HiddenField PDFGenBtnClicked = null;
. . .
PDFGenBtnClicked = new HiddenField();
PDFGenBtnClicked.ID = "pdfgenbtnclicked";
PDFGenBtnClicked.Value = "no";
this.Controls.Add(PDFGenBtnClicked);
...from the jQuery, like so:
$(document).on("click", '[id$=btnGeneratePDF]', function () {
$('[id$=pdfgenbtnclicked]').val("yes");
});
..and then have code like this on the server-side to kick off the calling of the method:
if (PDFGenBtnClicked.Value == "yes")
{
GeneratePDF(listOfListItems);
}
...but how can I cause this (last) bit of code to be called? Can I put a timer on the page, and have it check the status of PDFGenBtnClicked.Value every so often? This is probably possible, but almost certainly Goldberg-esque.
Who has a better idea?
UPDATE
Theoretically (I think!) this should work (non-Ajax way to indirectly run server-side code from client-side code):
0) Create the Timer
private Timer tmr = null;
1) Create the "Generate PDF" button and the Timer:
btnGeneratePDF = new HtmlButton();
btnGeneratePDF.Attributes["type"] = "button";
btnGeneratePDF.InnerHtml = "Generate PDF";
btnGeneratePDF.ID = "btnGeneratePDF ";
this.Controls.Add(btnGeneratePDF);
tmr = new Timer();
tmr.Interval = 3000; // three seconds
tmr.Tick += TickHandler;
tmr.Enabled = true;
2) Call the method when the Timer trips:
private void TickHandler(object sender, object e)
{
GeneratePDF(listOfListItems);
}
3) Run the code if the user selected the "Generate PDF" button:
private void GeneratePDF(List<ListColumns> listOfListItems)
{
if (PDFGenBtnClicked.Value != "yes")
{
return;
}
tmr.Enabled = false; // only run this once, after val has changed to "yes" by the user clicking the "btnGeneratePDF" button (set from "no" to "yes" in jQuery's response to the clicking of the button)
. . .
However, I have a breakpoint on the first line of GeneratePDF(), and I'm not reaching it, dod-durn it.
UPDATE 2
I even added another event handler, for init:
tmr.Tick += TickHandler;
tmr.Init += InitHandler;
tmr.Enabled = true;
message.Text = "Converting the data to a PDF file has been successful";
(I do see the message Text, although it's not true).
With breakpoints in both methods:
private void TickHandler(object sender, object e)
{
GeneratePDF(listOfListItems);
}
private void InitHandler(object sender, object e)
{
GeneratePDF(listOfListItems);
}
...neither is ever reached. Why not? Theoretically, this seems like it should work...(I know, everything works in theory).
What you're looking to accomplish can be done by webservices and ajax.
Jquery.ajax can be used to send a request to a webservice (or webpage, or whatever). Here is an example from one of my websites:
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "FoamServices.asmx/GetFoamNames",
data: "{'term':'" + $("#txtFoamName").val() + "'}",
success: function (data) {
//whatever you want to do with the data
},
error: function (result) {
alert("Error");
}
});
More information on this example can be found at Jquery.ajax website, but the gist of it is that I have a webservice set up, FoamServices.asmx and the method GetFoamNames in that webservice. GetFoamNames takes "term" in for a parameter. Upon success, I take the data I've received from that website and do what I want (check a true value, inject it into the page, whatever).
On the server side, here's my webservice:
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.Web.Script.Services.ScriptService]
public class FoamServices : System.Web.Services.WebService {
public FoamServices () {
//Uncomment the following line if using designed components
//InitializeComponent();
}
[WebMethod]
public string[] GetFoamNames(string term) {
List<Foam> foams = Foam.Read(term);
string[] foamNames = new string[foams.Count];
for(int i = 0; i < foams.Count; i++)
{
foamNames[i] = foams[i].FoamName;
}
return foamNames;
}
}
This is the basic set up for a webservice that also allows it to accept parameters from a javascript (JQuery) request.
What my service is doing is querying a search term against a database and returning the results. This is the basic setup for an autocomplete JQuery box.
You can adapt this to whatever you like, or you can also use ajax to call a webpage instead of webservice and have it do something.
Hope this helps!
The short answer to your question is that you'll have to use ajax, jQuery has some information regarding using it - https://learn.jquery.com/ajax/.
The longer answer is you'll need to do something like this:
$(document).on("click", '[id$=btnGeneratePDF]', function () {
$.get('/some/route/', function(result) {
//do something with the response, or not depending on your needs
}
});
I'm not familiar with Sharepoint so I can't offer any help on that side, but the basics are that you'll need to create a new page that fires off your PDF generation and access it using ajax, then handle the results in whatever way is appropriate.
My only suggestion is that if you want to only refresh part of the page without doing a full postback, use either AJAX, a callback, or an update panel. Update panels are very simple, but depending on what your button actually does may not be the best option. Just in case though, here is an example
<asp:ScriptManager runat="server" ID="sm">
</asp:ScriptManager>
<asp:updatepanel runat="server">
<ContentTemplate>
<asp:button id="YourButton" runat="server" Text="clickme" onclick="function" />
</ContentTemplate>
</asp:updatepanel>
This will not cause a full postback, and IMO is simpler than AJAX, but like I said may not be the most appropiate solution depending on your exact situation
Here is a link you may find useful from the MSDN site if you want to read up on it.

Trying to access server side variable from javascript

i have a page where in the form load i initialize a server side variable with value and i want to render that value in js section. i am working with asp.net webform apps.
my server side page load code
string errblankEmail ="";
protected void Page_Load(object sender, EventArgs e)
{
errblankEmail ="Hello World";
}
if (str == '') {
alert('<% =errblankEmail %>');
}
when i run the page then i am getting error message like
CS0103: The name 'errblankEmail' does not exist in the current context
and i also saw that my page_load is not getting called because i set break point there.
so guide me how to fix this problem. thanks
You have to make the variable public in order to access it.
public string errblankEmail ="";

Get data from JS variable and set in a ASP.NET variable

I want to pass data from one user control to another one, but i've tried several things to do it, and non of them worked, such as sessionStorage in JS, Session in ASPX, cookies in both of them.
This data is dynamic so I don't now how to transfer it, to the other user control.
I even tried to put aspx code in the javascript function (then when I click in the button it could trigger the code, but it doesn't work as well).
This button i refereed above is written in a literal control.
JavaScript Functions
this function is the LoadUsers UserControl
function getID(ID) {
sessionStorage.setItem("userID", ID);
}
this function is in the Access UserControl
function catchIP() {
var ID = sessionStorage.getItem("userID");
$('#<%= value.ClientID %>').val(ID);
}
UserControls
Load Users:
...
string _str = "<a href'#lastAccess' css='btn btn-success' onclick='javascript:getID(" + _id[_contForeach] + "); catchID();'>Access</a>";
_loadUsers.Controls.Add(new LiteralControl(_str));
Access:
How can I get access to the ID in the JavaScript function and apply it without using Page_Load
To pass information between the server side code and the client side code (JavaScript) use ajax
Ajax
So using jquery, have something like this function:
$.get('getuserid.aspx', function(response) {
//Do something with return response
});
then in the code behind getuserid.aspx.cs
private void Page_Load(object sender, System.EventArgs e)
{
Response.Expires = -1;
//required to keep the page from being cached on the client's browser
//set userid
Response.ContentType = "text/plain";
Response.Write(userid);
Response.End();
}

Call client script from button with submit behaviour false?

How do I call a client script function from a server side button click(with submit behaviour set to false) .
protected void Button4_Click(object sender, EventArgs e)
{
//System.Threading.Thread.Sleep(2000);
lbDateTime.Text=System.DateTime.Now.ToString();
ClientScript.RegisterClientScriptBlock(this.GetType(),"success","saveSuccess()");
}
You should set the OnClientClick attribute of the Button like
OnClientClick="saveSuccess(); return false;"
this way you keep the sumbit behaviour to false, and you also call the client script function.
Also, if you want to do this via server side code you can add this to your Page_Load
Button4.Attributes["OnClientClick"] = "saveSuccess(); return false;";
However, if you want to call the script after the "save" has completed, and you are using asynchronous jobs, and an UpdatePanel, then you should call
ScriptManager.RegisterClientScriptBlock(typeof(Page), "savescript", "saveSuccess();", true);
after the asynch job has finished, and the data have been saved.
ClientScript.RegisterStartupScript(this.GetType(), "success", "saveSuccess()", true);

Categories