launch two actions in one button ASP.NET - javascript

I'm developing a comment page in asp.net, this my page :
<form action="#">
<p><textarea id="textArea" rows="5" cols="30"></textarea></p>
<input type="submit" value="Submit" />
</form>
<p>Add some comments to the page</p>
And this is my javascript code :
window.onload = initAll;
function initAll() {
document.getElementsByTagName("form")[0].onsubmit = addNode;
}
function addNode() {
var inText = document.getElementById("textArea").value;
var newText = document.createTextNode(inText);
var newGraf = document.createElement("p");
newGraf.appendChild(newText);
var docBody = document.getElementsByTagName("body")[0];
docBody.appendChild(newGraf);
return false;
}
Until then, everything is fine, but I want when the user clicks the submit button, the button will trigger another action that will save the comment in the database.
How can I do this thing ?

Why don't you have a wrapper and still make it one function?
The addNode could have code to do both maybe based on something in the form?
You could have a submit function that wraps the addNode and addComment.
eg:
function handleSubmit()
{
addNode();
addComment();
return false;
}
EDIT: Since you want to call server code you have a couple of options. You can do it all via ajax and you would just need to implement the addComment function to call a server side event. See this article if you need help doing so:
http://www.dexign.net/post/2008/07/16/jQuery-To-Call-ASPNET-Page-Methods-and-Web-Services.aspx
The easiest way would be to change your button to an ASP.NET button and then implement the button click event which would call your server side method although this would cause a full page refresh.
A hybrid of the two, which is very easy to implement, would be to use an UpdatePanel. When you clicked your button you would get the look and feel of the AJAX solution but only need to know how to do all the server side code and let the UpdatePanel handle all the AJAX work. This method is a little heavier than just doing a raw ajax call but it is significantly more simple to do.
You can read up on UpdatePanels at: http://msdn.microsoft.com/en-us/library/bb399001.aspx

Instead of using an HTML input tag, use asp:Button, like so:
<asp:Button ID="btnSubmit" runat="server" OnClick="btnSubmit_Click" />
What this says is, use a Button that calls the "btnSubmit_Click" method whenever it is clicked on, and run this on the server (not on the client machine).
Then in your code-behind (you do have a code-behind, right? e.g., nameOfPage.aspx.cs), you can add the aforementioned btnSubmit_Click method:
protected void btnSubmit_Click(object sender, System.EventArgs e) {
// interact with database here.
}

Related

React/javascript component to send data back to aspx

I've a legacy ASP.NET application, which I'm trying to modernize. I've a page
MyPage.aspx, and its codebehind MyPage.aspx.cs
I've replaced a custom user control (which does a fileupload) with a custom react component. The react component is working as expected. The old ascx usercontrol had an event handler which is defined in 'MyPage.aspx.cs'as follows.
protected void asyncFile_FileUploaded(object sender, FileUploadedEventArgs e)
//logic to set the uploaded file's name etc for saving.
}
Nowthat the custom control is replaced with an empty DIV, where the react component is being mounted, I'm left with no option to call my C# logic in the 'MyPage.aspx.cs' codebehind file.
I've created a 'CreateProperty.aspx.js' file which is responsible of initializing my react component inside the .aspx page, and below is the contents of this file.
$(document).ready(function () {
if ($('#Myupload').length) {
ReactDOM.render(
<Upload id="pictureupload2"
onChange={onChange}
setBusyState={onBusy}
onUploadSucceeded={onUploadSucceeded}
/>,
document.getElementById("Myupload")
);
}
});
function onChange(e) {
console.log(e);
}
function onBusy(e) {
console.log(e);
}
function onUploadSucceeded(e) {
console.log(e);
}
Once the react component has done the uploading, it calls the function onUploadSucceeded() with my required parameters. But how will I pass that value back to my MyPage.aspx.cs file ?
Please help.
Drop in a standard asp.net button on the form.
Move the code you have/had for the previous event into that button code stub
eg:
protected void asyncFile_FileUploaded(object sender, FileUploadedEventArgs e)
//logic to set the uploaded file's name etc for saving.
}
So, move the above code to the button (style="display:none) to hide it.
AND OF COURSE don't copy the event stub code!!!.
Now, in your js function, do whatever and simply "click" on that button.
The bonus here is you get the badly needed post back when the client side js/ajax runs.
So, you have this:
function onUploadSucceeded(e) {
console.log(e);
document.getElementById('<%= btnOkUpLoad.ClientID %>').click();
So, the above is nice. I mean you could do a js __DoPostBack(); in js, but then you have to pass some parameters, and then client side in the on-load page event, detect the parameters (a pain to wrire up).
So, anytime I want to run code behind from js? Just drop in a asp button, write the code stub for that button, and then client side, use the above ".click()" to run that code. As noted, in MOST cases you want a post back anyway - which is what a asp.net button does for you.
Edit: now I said we want a post back in most cases? Well, I mean when we are all said and done - and thus this button click makes sense. We certainly don't want needless post backs - but when you do, and when you want to run+call a code stub, the this button trick is nice. Just use style="display:none" to hide it from view - but js code can still use the .click() to run (click) the button for you))

Stop page reload of an ASP.NET button

NET application, I have inserted a button that call a Javascript function (OnClientClick event) and a VB.NET function (OnClick event)
<asp:Button OnClientClick="jsfunction() " OnClick="vbfunction" Text="Submit" runat="server" />
The problem is that when I click the button, it refreshes the page and delete the content of the text boxes.
I have tried with inserting return false; on the OnClienClick event, but it doesn't execute the OnClick Event.
How can I avoid the page reload ?
P.S.: At the end of the Javascript function a new window is opened window.open(newWindow.aspx), but I want that the first page mantain the value inserted by the user in the Text Boxes.
Thanks in advance :)
You need to use return statement at two points.
OnClientClick="return jsfunction();"
function jsfunction()
{
//
return false;
}
OR, you can return false after the function call like this.
OnClientClick="jsfunction(); return false;"
Note if you want to do postback conditionally then you need to return true or false.
OnClientClick="return jsfunction();"
function jsfunction()
{
if(conditionForPostBack)
return true;
else
return false;
}
or you can disable the submit behaviour. By default asp.net renders button as submit button. if you disable submit behaviour it will render button as button type
<asp:Button UseSubmitBehavior="false" OnClientClick="jsfunction() " OnClick="vbfunction" Text="Submit" runat="server" />
But with this code it will not fire server side event "OnClick"
if you are not going to trigger the button with C# Codebehind function, then you dont need to use asp:Button. Therefore you can use a regular html .
<button id='btn_1' onclick='ajax_function()'>Button</button>
html button is much easier and faster. if you use asp:button, then you should use clientid() function to catch the control to trigger the ajax.
Searching for the same thing as you i find a patch:
If you call a method server side, you can use AJAX with the update panel, but that didn't worked for me. But you can save what you want in Session, so you have it as far as Session lasts.
// Save at SessionParameter the elementToSave we want.
this.Session["SessionParameter"] = elementToSave;
// Retrieve the info from the Session
ElementYouNeededToSave = (TypeOfTheElement)Session["SessionParameter"];
Hope this will help someone in my situation.

To give a confirm pop up box within event for submit button and allow or not allow to submit

I have submit button. On its click I have to check a paricular field's value from database and then give a pop up for confirmationa and then depending on yes or no allow/disallow save.How can i do so..
On using confirm JS function it passes the statement and runs the Save procedure anyway.
my button's event
protected void btnSubmit_Click(object sender, EventArgs e)
{
string ListExam = string.Empty;
DataTable dt = BussObjGoalCert.CheckPlannedStatus(custObjGoalCert);
if (dt.Rows.Count != 0)
{
for (int i = 0; i < (dt.Rows.Count); i++)
{
ListExam = ListExam + (dt.Rows[i]["MultipleExamPlanned"]) + ";";
}
lblExamMultiple.Text = ListExam;
string myScript2 = "confirm('Unselected exam planned under other certification will also be unplanned.Do you wish to continue?');";
ClientScript.RegisterStartupScript(this.GetType(), "myScript", "confirm('Unselected exam planned under other certification will also be unplanned.Do you wish to continue?');", true);
}
Result = BussObjGoalCert.InsertGoalCertification(custObjGoalCert);
}
SO what I am doing is checking some data from backend and then trying to conditionally call the confirm function.
It IS CALLED but then Insert statement is also run irresepective of what the person chooses.
How can the database check be done within JS function.I need to do it in code behind. and yet allow/disallow complete save.How is this to be accomplished. I am not using OnCLientCLick as suggested in the answers.
Try this
If you have asp button
<asp:Button runat="server" ID="btn"
OnClientClick="return confirm('Are you surely want to submit (server button) ?');"
Text="Server button" />
If you have submit HTML button
<input type="submit"
onclick="return confirm('Are you surely want to submit (client button) ?');"
value="Client button" />
UPDATE
If you want to do this
Execute some server side code
Ask user for some confirmation
On user's confirmation execute some more server side code
Then should do following
Create a web service.
Use Jquery or Javascript to execute your server side code through that web service.
Display confirm box on complete(success) event of your web service request.
If user click's on YES perform a server side potback or perform one more web service request to execute the code to be executed on user's confirmation.
I think you are trying onclick event on submit button.
try onsubmit="return confirm('Are You sure to submit')" within form element
There is one solution for your problem.please follow these steps :
1.)On button's OnClientclick event call pagemethod and pass value in it which you want to check in Database.
2.)pagemethod is used to call server side static methods on client side and return result.
3.)Then return bool value from that in true if data exist and false if new.
4.)When flag is true then show confirmation box if confirmation is true then call server method again and update info and then return true to OnClientClick event.
OR
if confirmation is false then return false to OnClientClick event.
You can check my artical HERE.Hope this helps you.If you need more detail then please let me know.
try this
<asp:Button ID="btnsave" runat="server" Text="Save" OnClientClick="javascript:return Checkdelete();"/>
function Checkdelete() {
return confirm("Are you sure you want to Save the records");
}

ASP.net - Button - Javascript Confirm dialog - execute SOME server-side code?

I have a simple ASP.net page where users can edit information about themselves.
When "Edit" button is clicked, the form goes into edit mode and I display "Save" and "Cancel" buttons, which behave as expected.
What I want to do is this:
When "Save" is clicked, display a Javascript Confirm dialog asking the user if they want to send an email to the other users to inform them of the update just made.
If user says OK, then execute all server-side code to save the data, AND send an email.
If user says Cancel, then execute all server-side code to save the data, WITHOUT sending the email.
So, I need the javascript box to set a flag which can then be read server-side, somehow... then I can do something like:
Sub btnSave_Click(sender, e) Handles btnSave.Click
'Save all the data
If sendEmail Then 'This flag set by reading result of javascript Confirm
'Send the email
End If
End Sub
I know how to add a Confirm box to the button Attributes, and have done so. I'm looking for an answer on how to read the result of that box on server side... in other words, I ALWAYS want the Page postback to happen (from clicking the button), but only SOME of the event-handler code to execute.
Hope that makes sense.
Thanks
Matt
Create a hidden field, and set the value of that field based on the result of the confirmation. You haven't shown the code/HTML for your button or form, but can you fit something like this into it:
<input type="hidden" id="sendEmail" name="sendEmail" value="" />
<input type="submit" value="Save" onclick="promptForEmail();" />
<script>
function promptForEmail() {
var result = Confirm("Send everybody an email?");
// set a flag to be submitted - could be "Y"/"N" or "true"/"false"
// or whatever suits
document.getElementById("sendEmail").value = result ? "Y" : "N";
}
</script>
There are several ways to do it but I am going to use asp:HiddenField. In javascript, after user confirms, let its result to be set in the hidden field. And in server side, you can access it like any other asp.net control.
So
your aspx:
<asp:HiddenField ID="HiddenField1" runat="server" Value="" />
CodeBehind:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
var result = HiddenField1.Value;
}
}
Javascript:
//after confirm call this
function SetValue(val)
{
document.getElementById('HiddenField1').value=val;
}

change text of asp.net button with javascript

I have a form submit button that has asp.net validators hooked up to it. If I make a javascript function to change the text to processing on click it does not work. The button flags the validators and also causes the whole page to post back. Heres the code I have:
C#
protected void Page_Load(object sender, EventArgs e)
{
btnPurchase.Attributes["onClick"] = "submit()";
}
Html
<script type="text/javascript">
function submit() {
document.getElementById("ctl00_ContentPlaceHolder1_btnPurchase").value = "Processing";
};
</script>
My goal is to change the buttons text to purchasing onclick if the form passes validation, and then in my code behind it will change back to the original value once the form posts back.
I ran across this solution which works 100% perfect. I'm using the script manager with update panels...
<script type="text/javascript">
// Get a reference to the PageRequestManager.
var prm = Sys.WebForms.PageRequestManager.getInstance();
// Using that prm reference, hook _initializeRequest
// and _endRequest, to run our code at the begin and end
// of any async postbacks that occur.
prm.add_initializeRequest(InitializeRequest);
// Executed anytime an async postback occurs.
function InitializeRequest(sender, args) {
// Get a reference to the element that raised the postback,
// and disables it.
$get(args._postBackElement.id).disabled = true;
$get(args._postBackElement.id).value = "Processing...";
}
// Executed when the async postback completes.
function EndRequest(sender, args) {
// Get a reference to the element that raised the postback
// which is completing, and enable it.
$get(args._postBackElement.id).disabled = false;
$get(args._postBackElement.id).value = "Purchase";
}
</script>
I just asked a very similar question (which was answered):
ASP.NET Custom Button Control - How to Override OnClientClick But Preserve Existing Behaviour?
Essentially you need to preserve the existing behaviour of the submit button (__doPostBack). You do this with Page.GetPostBackEventReference(myButton).
However with validation it's more difficult, so you'll need to do page validation inline (Page.Validate()) or create a custom control like i did and override the OnClientClick and PostBackOptions members.
Custom control is better, as i can now just drop this control on any page i want this behaviour.
You could do the same and expose a public property:
public string loadingText {get; set;}
Which could be used to customise the loading text on each page.
You basically need to set the onclick attribute to do the following:
onclick = "if (Page_Validate()) this.text = 'Processing';{0} else return false;"
{0} should be the regular postback action, retrieved from Page.GetPostBackEventReference.
The resulting logic will be: on click, validate the page, it it succeeds, change the text and postback, if it fails, return false - which will show the validation on the page.
Have the button set to default text "Submit" in the HTML, then wrap the above logic in !Page.IsPostBack so it will reset the text on form submit.
Hope that helps.

Categories