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;
}
Related
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());
}
}
}
I have this code behind in my ASP.NET 4 Web Forms app:
Protected Sub BTNSave_Click(sender As Object, e As EventArgs) Handles BTNSave.Click
If saveOnDB() Then
showOkAlert()
Else
showErrorAlert()
End If
End Sub
I need to show a client alert when something done in the code behind has gone OK or an error has happened. Any idea?
I haved tied Response.Write("<script>alert('Successfully added');</script>") but this never works and even creates an error in the browser's console: "Uncaught Sys.WebForms.PageRequestManagerParserErrorException: Sys.WebForms.PageRequestManagerParserErrorException: The message received from the server could not be parsed."
Also I don't use OnClientClick because it triggers the javascript before the codebehind.
I do something similar. I've hacked some working code to simplify it as an example for your particular use:
private void RegisterJavascriptForUpdatePanelExample(UpdatePanel myUpdatePanel, string myMessage)
{
const string JAVASCRIPT_TEMPLATE = "javascript: jQuery(function($) {{ alert({0}); }});";
const string SCRIPT_KEY_TEMPLATE = "KeyForRegisterJavascriptForModalPopup_{0}";
string scriptkey, scriptstr;
scriptkey = string.Format(SCRIPT_KEY_TEMPLATE, myUpdatePanel.ClientID);
scriptstr = string.Format(JAVASCRIPT_TEMPLATE, myMessage);
ToolkitScriptManager.RegisterClientScriptBlock(myUpdatePanel, myUpdatePanel.GetType(), scriptkey, scriptstr, true);
}
In this example, a simple JavaScript alert() is called to display your message, like this:
RegisterJavascriptForUpdatePanelExample("A-OK!");
Of particular interest is the ToolkitScriptManager.RegisterClientScriptBlock function. There are several variations of this, depending if the JavaScript code should be embedded and executed within an UpdatePanel, or when the page loads, or other situations. It can be kind of confusing to decide which function is needed, but it's just what you need.
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
I have written a custom web control that validates some input to a textbox client-side. The associated JavaScript is an embedded resource. As part of the validation process the JavaScript displays a confirm alert box.
I want to be able to set the message of the alert from a property of web control, in a similar way to the standard asp.net validation controls have the ErrorMessage property.
Can anyone advise me on the best way to splice this property into my embedded JavaScript?
Embedded js function
function checkDeduction(sender, eventArgs) {
var dNewVal = eventArgs.get_newValue();
if (dNewVal > 0) {
var bRetVal = confirm("custom msg here");
if (!bRetVal) {
dNewVal = dNewVal * -1;
sender.set_value(dNewVal);
}
}
}
To achieve this I added a custom attribute to my custom control on the PreRender event:
protected override void OnPreRender(EventArgs e)
{
this.Attributes.Add("ErrorText", "custom error text from public prop");
...
base.OnPreRender(e);
}
I was then able to hold of the error message client-side like so:
confirm(sender.getAttribute('ErrorText'));
Job done!
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);