I want to use a javascript function inside a c# function
protected void button1_Click(object sender,EventArgs e){
//javascript function call ex.
/*
boolean b=the return of:
<script type="text/javascript">
function update() {
var result = confirm("Do you want to delimit the record?")
if (result) {return true;}
else {
return false;
}
}
</script>
*/
}
how can i do such a thing? i want when user press yes return true and i know he pressed yes...can i do so?
If you're trying to add JavaScript to your page from asp.net, you can use the ClientScript class.
string script = "function update() { var result = confirm(\"Do you want to delimit the record?\") if (result) {return true; } else { return false; } }";
ClientScript.RegisterClientScriptBlock(this.GetType(), "someKey", script, false);
If you're trying to call (client side) JavaScript functions from your asp.net code behind, then absolutely not. When the page posts and your C# is run, any JavaScript that was on the page no longer exists.
You're mixing two different technologies. C# runs on the server. It renders an HTML page (which may include Javascript). This page is then sent to a client's browser, where Javascript finally gets executed.
In Javascript you can prompt user about record deletion or whatever, and then you have to either navigate to another page or use AJAX to send result to the server.
I suggest that you get a good ASP.NET book. It will clear many uncertainties for you.
If you're putting this message on an <asp:Button> with postback just add the confirm dialog to the OnClientClick attribute like so:
<asp:Button ID="Button1" runat="server"
OnClientClick="return confirm('Do you want to delimit the record?');" />
If you're simply trying to create the functionality of letting the server know that a button was clicked, you're over complicating things. If you really need to dynamically insert Javascript then what Adam mentioned is worth looking into. But I highly doubt that this is the correct approach for what you're trying to do.
You should really only dynamically insert Javascript when you're worried about performance AND you have a lot of content to send.
If dynamically inserting Javascript (ie. lazy loading) is not your main concern, then here is a very simple example of what most folks would usually do to achieve the functionality you're aiming for.
Related
I am trying to create a textbox which updates the text in it after a key has been pressed, so I have created a program inside the class of the page which executes the function I want. The program works fine, my question is how do I call that program in the javascript function when onkeypress event happens:
//My text box:
<asp:TextBox ID="MyBox" onkeypress="AutoText(); return false;" runat="server"
Width="400px" ToolTip="Text?" CausesValidation="True" AutoPostBack="True">
</asp:TextBox>
//My function
function AutoText()
{
var i;
i = Class1.BoxTextChanged(object sender, EventArgs e);
}
I know the function doesn't work and that's not how to call a program from a c# class in JavaScript, I am only asking if it's possible how to do it.
Note that I did research this as much as I can, maybe the searches I did were of no use because there are so many subjects to this topic or maybe I just did it wrong :P
You are mixing client and server side. ASP.NET is executed from server side, and Javascript is executed from client side.
So, you cannot call an ASP.NET function directly from Javascript in your case, because the server cannot access to the client side textbox.
Your solution is to write this function in Javascript. It could be something like that :
function boxTextChanged(text) {
getElementById('textBoxToUpdate').value(text);
}
By the way, I just want to add that you can call ASP.NET directly in Javascript using ajax, but server side will never be able to update directly DOM on the client side. Usually, ajax is used to get datas from server.
you can call the web method onkeypress envt and pass it the value of text box which will update the database with text box value.
which is done by javascript so that you did not required post back of whole page so it improve your performance.
I'm working on an ASP.Net project, with C#.
Usually, when I need to put Buttons that will execute some methods, I will use the ASP Controller (Button) inside a runat="server" form.
But I feel that this really limits the capabilities of my website, because when I used to work with JSP, I used jquery to reach a servlet to execute some codes and return a responseText.
I did not check yet how this is done in ASP.Net, but my question concerns controllers and the famous runat="server".
When I add a runat="server" to any HTML Element, I'm supposed to be able to manipulate this HTML element in C# (Server-Side), and this actually works, I can change the ID, set the InnerText or InnerHtml, but the thing that I can't get, is why can't I execute a method by clicking on this element?
The "onclick" attribute is for JavaScript I think, and OnServerClick doesn't seem to work as well. Is it something wrong with my codes? or this doesn't work at all?
You will have to handle the click in the div using the Jquery and call
server-side methods through JQuery
There are several way to execute server side methods by clicking on a div or anything on your page. The first is mentioned __dopostback, second is handling the click in javascript or with jQuery and calling a function in a handler or a page method in a webservice or a page method in your page behind code.
Here is the handler version:
$("#btn1").click(function() {
$.ajax({
url: '/Handler1.ashx?param1=someparam',
success: function(msg, status, xhr) {
//doSomething, manipulate your html
},
error: function() {
//doSomething
}
});
});
I think the second version is better, because you can make a partial postback without any updatepanel, asyncronously. The drawback is, the server side code is separated from your page behind code.
Handler:
public class Handler1: IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "application/json";
var param1= context.Request.QueryString["param1"];
//param1 value will be "someparam"
// do something cool like filling a datatable serialize it with newtonsoft jsonconvert
var dt= new DataTable();
// fill it
context.Response.Write(JsonConvert.SerializeObject(dt));
}
}
If everything is cool, you get the response in the ajax call in the success section, and the parameter called "msg" will be your serialized JSON datatable.
You can execute a method from jquery click in server, using __doPostBack javascript function, see this threat for more details How to use __doPostBack()
Add this code in your jquery on div onclick and pass DIv id whcih call click
__doPostBack('__Page', DivID);
On page load add this code
if (IsPostBack)
{
//you will get id of div which called function
string eventargs = Request["__EVENTARGUMENT"];
if (!string.IsNullOrEmpty(eventargs))
{
//call your function
}
}
Make the div runat="server" and id="divName"
in page_Load event in cs:
if (IsPostBack)
{
if (Request["__EVENTARGUMENT"] != null && Request["__EVENTARGUMENT"] == "divClick")
{
//code to run in click event of divName
}
}
divName.Attributes.Add("ondivClick", ClientScript.GetPostBackEventReference(divName, "divClick"));
Hope it helps :)
if you are referring to divs with runat="server" attributes, they don't have onserverclick events, that's why it doesn't work
I have a c# asp.net page and an update function which will update the database. In this function I would like to call some client side javascript. I've read a lot about registering a start up script in page_load() but this is always trigger on page load (funny that!)
How would I register then call a script inside my update function? Triggered when a user clicks the "update" button. I have tried the following (inside my function)
protected void doUpdate(object sender, EventArgs e) {
string jScript;
jScript = "<script type=text/javascript>alert('hello');<" + "/script>";
ClientScript.RegisterStartupScript(GetType(), "Javascript", jScript);
}
but it isn't fired. Any ideas? Many thanks.
[update]
It's now working - the function looks like this
protected void doUpdate(object sender, EventArgs e) {
ScriptManager.RegisterStartupScript(this, GetType(),"Javascript", "cleanup();",true);
}
Cleanup() is the javascript function in my HTML. Thanks for the help guys :)
If the control causing the postback is inside an UpdatePanel you need to use
ScriptManager.RegisterStartupScript
You can't 'execute' client side scripts from the web server (the client knows who the server is, but not the other way around).
The only way to overcome this limitation is by a. create a long-polling process that requests something from the server, the server doesn't complete the request till it has something to return (then client side it makes another request).
What you are really looking for is websocket (duplex) enabled communication. You can check out alchemy websockets or SignalR (has a pretty nice library with dynamic proxy generation).
The reason why that 'script always works on Page_Load' is because it effectively injects your script tag into the html returned for the page requested.
Your Update button is likely using the standard ASP Button behavior, meaning it is type="submit" when it is rendered. Since that's the case, you can just use:
Page.ClientScript.RegisterOnSubmitStatement
Keep in mind that will register a script for every postback, not just the Update button. So, if you only want some javascript run on clicking Update, you would need to check if the EventTarget is UpdateButton.ClientID. Also, RegisterOnSubmitStatement always adds the <script> tags, so don't include those in the javascript statement.
An even easier solution, the ASP Button itself also has an OnClientClick property. This will run client-side code (javascript) when the button is clicked in the browser.
I know this is a basic question, but I am curious as to what the different options are, and what the best practice would be.
If I have a form that is responsible for saving reservations into a system, how can I prevent the form from being posted twice if the user hits the button twice really quickly?
I know there are a few ways in which I can accomplish this, but I am not quite sure which is the standard way of preventing this. Partially because I am new to web forms, and am used to dealing with MVC.
Thanks ahead of time.
I've used two approaches to this problem:
Use a token based approach. Each page has a hidden input with the current random token. This token is also stored in the user's session. Once the postback occurrs, I compare tokens and, if they are valid, generate a new session token and continue processing. When the second postback occurs, the token no longer matches and prevents processing.
Use javascript to disable the submit button. If you take this approach, and need the button event handler to fire, you'll need to create a hidden input with the name attribute of the button before submitting. The hidden input is required because disabled inputs do not end up in the post data.
I would recommend a client-side onClick event handler that disables the button or makes it invisible, preferably the latter, and replace the button with a label that reads "Processing..." or something like this
I have been using something like this when using an asp:Button for submitting:
1) Set the submit button's UseSubmitBehavior="false"
2) Set the submit button's OnClientClick="pleaseWait(this, 'Please Wait...');"
3) Include javascript code in the page:
function pleaseWait(obj, message) {
if (typeof(Page_ClientValidate) == 'function') {
if (Page_ClientValidate()) {
obj.disabled = true;
obj.value = message;
return true;
}
}
return false;
}
This solution is nice because it is simple but still accounts for client-side javascript validations. It isn't perfect, because it still relies on Javascript, which could be turned off, but that's unlikely to be done by someone who doesn't have the sense to click once and wait for a response. :)
Easy way - use the ajax AnimationExtender control.http://www.asp.net/ajaxLibrary/AjaxControlToolkitSampleSite/Animation/Animation.aspx
Simply attach the extender to the button and add a disable action.
<asp:Button ID="CopyScenarioButton" ClientIDMode="Static" OnClick="CopyScenarioButton_Click"
OnClientClick="setTimeout( function() {$('#CopyScenarioButton').attr('disabled', 'disabled');},0)"
EnableViewState="false" Text="Save New Scenario" ToolTip="Save New Scenario"
CssClass="btnNormal" runat="server" />
or the later version that includes some validation first:
function PreSaveHybrid() {
var doSave = PreSave();
if (doSave !== false) //returns nothing if it's not a cancel
setTimeout(function () { $('#btnSave').attr('disabled', 'disabled'); }, 0);
return doSave;
}
With ASP.NET, how do I prompt the user for a yes/no question and getting the result back to my .ascx?
So far I can open a confirmation dialog with use of Javascript, but I can't return the value. But I don't know if this is the right approach.
You can use standart JavaScript confirm() function to show popup and do Post Back in case of Yes or No. For example:
if (confirm('Question')) {
__doPostBack('', 'Yes_clicked');
} else {
__doPostBack('', 'No_clicked')
}
Then on server in Page_Load() method do:
if (IsPostBack)
{
var result = Request.Params["__EVENTARGUMENT"];
}
You can also do it async by specifying the first parameter of __doPostBack() function as ID of any update panel.
This is not a good practice to do this. you can get your confirm using javascript and postback or callback result to server.
but if you want to do this, this will help you :
A Simple ASP.NET Server Control: Message Box & Confirmation Box
add this in head of source
function confirm_Edit()
{
if (confirm("Are you sure want to Edit?")==true)
return true;
else
return false;
}
call it like this
If you insist on using webforms, another solution could be the AJAX Control kit. Simply create a ModalPopup and have you confirm buttons inside that.
Read more here:
http://www.asp.net/ajax/ajaxcontroltoolkit/Samples/ModalPopup/ModalPopup.aspx
You need to use ajax, or to make a postback to the server.
Your c# code is server side and the javascript is client side.
If you use the ajax extensions for asp .net you can use javascript page methods:
PageMethods.YourMethod(confirm('your text'), OnSuccess, OnFailure);
I use this. As far as I know it prevents the rest of the button event from executing.
btnMyButton.Attributes.Add("onClick", "return confirm('Are you really sure?')");
Another option is to show yes/no:
<script>
function AlertFunction() {
if (confirm('Are you sure you want to save this thing into the database?')) {
$('#ConfirmMessageResponse').val('Yes');
} else {
$('#ConfirmMessageResponse').val('No');
}
}
</script>
to handle it from .net side:
string confirmValue = ConfirmMessageResponse.Value;
if (confirmValue == "Yes")
{...}
string confirmValue = ConfirmMessageResponse.Value;
showing error in this line when using in .net side