Call client script from button with submit behaviour false? - javascript

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);

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());
}
}
}

ASP.NET - Call javascript validation function before submitting form

I need to implement some 3rd-party field validation in our site's forms. Currently, the validation of our form fields is done by using ASP.NET validators (required, regex) and I'd like to continue use of these on the fields where we won't be using the new validation. The company providing us with the new validation services gave us all of the code to integrate into our site to get the new validation functioning, and the basic implementation just requires us to call a javascript method that reads the values of specified fields and validates them via a few service calls. Also, the implementation requires that the form initially has the onsubmit="return false;" attribute set.
The issue that I'm running into is when the validation script is attempting to submit the form, (after a post-validation function removes the form's onsubmit attribute) since event validation is turned on (not an option to turn off), the page throws the exception "Invalid postback or callback argument". Perhaps I've provided an excess of details to give context, but maybe the question boils down to: Can you submit an ASP.NET form using javascript if event validation is enabled without causing this error? And if so, how?
You can invoke a post back in your JavaScript function, like this:
<script type="text/javascript">
function DoValidation(parameter)
{
// Do calls to validation services here
// If all validation passes, then call this
if(valid) {
__doPostBack('btnSave', parameter)
}
}
</script>
<asp:Button id="btnSave" runat="server" OnClientClick="DoValidation()"
Text="Save" />
Note: btnSave is a made up name, but it should represent the server-side control that would normally be doing the post back.
Now in your page's Page_Load event, you can determine who initiated the post back and any data sent with it, like this:
protected void Page_Load(object sender, EventArgs e)
{
// Get the control that caused the post back (btnSave)
Request["__EVENTTARGET"];
// Get the parameter value (parameter)
string parameter = Request["__EVENTARGUMENT"];
}
Yes, you can. Something like this, and please bear with me, this is merely pseudo code.
<header>
<script type="text/javascript">
function JavaScriptSave()
{
// Validations here
if(passed)
{
__doPostBack('<%=MyButton.ClientID %>','OkToSave');
}
}
</script>
</header>
<asp:button id="MyButton" runat="server" Text="Submit Button" OnClientClick="JavaScriptSave()" />
Then on the back side:
protected void Page_Load(object sender, EventArgs e)
{
string passedInValue = Request["__EVENTARGUMENT"];
if(passedInValue = "OkToSave")
{
// perform save function here
}
...
if(IsPostBack)
return;
}

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();
}

value from javascript is not returning to c# in the application in Visual Web GUI

I have written a java script function in the skin file of the visual web Gui application which returns some value too. Now i am invoking the java script method from code behind.
public void XYZ( string message)
{
this.InvokeMethodWithId("testCall", message);
}
And javascript function is:--
function testCall(strGuid, txt) {
alert("hai Java script fired..");
return txt+ 'returned from JavaScript';
}
I want the value returned from JavaScript in the application. how can i achieve it. Is there in other method to invoke the methods of JavaScript?
I want something like this:--
public void Conect( string message)
{
string returnedvalue = this.InvokeMethodWithId("testCall", message);
}
Javascript is executed on the client so the return won't make it to the server.
A solution could be to use AJAX to send that value to the server. Stack Overflow is full of answers about AJAX.
Here's a good example.
#Amish Kumar,
As noted by other replies already, the client-side and server-side are not directly connected in web programming. The client is always the initiator of every request, and the server-side's "purpose" is to render a response, which will then be returned to the client for processing, in Visual WebGui this is usually some UI update processing. This basically means that your client script will not execute until the server-side has finished rendering the response, and the only way the client can get some message back to the server is to issue another request.
Think about how you need to use the MessageBox in Visual WebGui for instance. In order to receive the "response" from the MessageBox, you need to supply a callback handler in your server-side code, and then your server-side code will have completed creating the response, which is returned to the client. The client updates its UI and on some action to the MessageBox dialog, it sends a new request to the server, which interpretes the action and invokes your callback handler. In the callback handler you use Form.DialogResult to get the user action.
A very basic way to make this work in custom Visual WebGui code could be like the following code on a Form:
private void button1_Click(object sender, EventArgs e)
{
SendClientMessage("This is a test");
}
public void SendClientMessage(string strMessage)
{
System.Text.StringBuilder sb = new StringBuilder();
sb.AppendLine("var objEvent = mobjApp.Events_CreateEvent('{0}', 'MessageEvent');");
sb.AppendLine("mobjApp.Events_SetEventAttribute(objEvent, 'Msg', '{1}');");
sb.AppendLine("mobjApp.Events_RaiseEvents();");
this.InvokeScript(string.Format(sb.ToString(), this.ID, strMessage));
}
protected override void FireEvent(Gizmox.WebGUI.Common.Interfaces.IEvent objEvent)
{
if (objEvent.Type == "MessageEvent")
MessageBox.Show(objEvent["Msg"]);
else
base.FireEvent(objEvent);
}
This code will not work unless you set your Visual WebGui applicaton for no Obscuring. In order for this code to work on an obscured application, you would need to add the JavaScript as an obscured JavaScript resource and it would work fine.
Palli
enter code here

asp.net jquery newbie question

I have a webform that contains a file upload button.
when I click on the button to upload the file, the C# code behind contains some code in the event handler that I want to execute first before jquery executes.
<script>
$(document.ready() {
$('.uploadButton').click(function() {
// do some additional processing *AFTER* code behind stuff executes
});
}
</script>
// In my ASP.NET C# code behind
protected void uploadButton_Click(object sender, EventArgs e)
{
// Code to fire off here *FIRST* before jquery executes
}
Is something like this possible? I know I can implement a jquery post in my javascript, but since I have most of the code already laid out (and am changing this on a client request), I was just wondering if something like this was possible.
It's not possible
The OnClick and jQuery event handlers are executed first and only after that the page is posted back and you're able to run the code in in your server.
The best thing that you can do is to use $.ajax
here's some code to help you.
In your code behind
[WebMethod]
public static string uploadButton_Click(string name)
{
return "Good bye World! by" + name ;
}
And in js file
$(".uploadButton").click(function(){
$.ajax({
type: "POST",
url: "PageName.aspx/uploadButton_Click",
data: "{'Name':'Mr.X'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
alert(msg.d) // will show up an alert box with Good bye world by Mr.X
}
});
});
You don't need to use the jQuery click handler. Wrap your code in a function and assign that function name to the OnClientClick property of the button. You can return false to prevent the post-back from processing.
http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.button.onclientclick.aspx
Ajax is the best option to choose. If you dont wannna use AJAX, then probably u can do this(perhaps the dirty-logic)
Do nothing with jQuery before the server is hit. In your code-behind
// In my ASP.NET C# code behind
protected void uploadButton_Click(object sender, EventArgs e)
{
// Code to fire off here *FIRST* before jquery executes
string strClientQuery = #"<script type="javascript"> $(document.ready() {
$('.uploadButton').click(function() {
// do some additional processing *AFTER* code behind stuff executes
});
} </script>";
Response.Write(strClientQuery);
}
If you want to keep the script strictly in client-side(i.e aspx page), then create the query as string in the aspx and pass it as an input to the page(through _EventTarget and in code-behind get the string and do response.write If you find the answser is useful, please take a few seconds to rate it

Categories