I have a bunch of text boxes and a save button to update something. When I click Save I have code that determines whether they are correctly filled in, in the code behind file.
If they are not correctly filled in, I want to display an error message in the form of an alert.
What is the best way to do this? Pressing the button obviously makes the page postback, so I thought about adding something to the URL like mypage.aspx?errormessage=blahblah but I don't know if this is the best way or even how to do it...
Any suggestions?
Modal alerts are bad, as are postbacks. Try to check as much as possible on the client-side without a round-trip to server. See jQuery Validation plugins for a less intrusive way of validation.
Could you use a CustomValidator to trigger client side script that shows a alert box?
You could use the ClientScript.RegisterStartupScript() method in the server side error handling code to write a javascript snippet which calls alert('message'), something like this
private void ShowErrorMessage(string message)
{
string script = "alert('" + message + "');";
ClientScript.RegisterStartupScript(typeof(MyPage), "errorScript", script, true);
}
But I would recommend you use a validator instead. If you implement your own custom validator, you can make it emit client-side script which can run before the submit, to avoid the postback altogether.
A good thing about validators is that their error messages can be displayed in a ValidatorSummary on the page, avoiding the ugly alert box.
First of all I won't recommend showing an modal alert box to the user.
You can call a javascript function from the server side code and in that function you can pop out the error.
Or you can issue an AJAX request and after the validation on server side you can send back a response to the client.
ASP.NET's various validation controls (with client-side validation enabled), coupled with proper error messages and/or summary message will be good enough for most scenarios.
For 'AJAX feel and behaviour', put the controls into an updatepanel will be easy to implement too.
Use ye olde Validators as much as poss, they render out some javascript to the client so yu can do alot of validation using these controls and only when they are all satisfied does it allow the page to submit.
They do fire on every submit so if you don't want every submit action to fire them you make the controls part of a validation group.
They can validate input using regular expressions, make sure a field has a value and there is a few more as well.
Then there is property to declare a 'message' and a control to show all the validator messages. All very swish and built right into the IDE.
Go check out the validator controls.
Try the following code in your button click event:
string strErr="Error!";//Put your error message here
ClientScript.RegisterStartupScript(GetType(), "scrptName", "javascript: alert('"+strErr+"'); ", true);
It will show an alert message.
Else put a label on your aspx page and set visible false in page_load event.
When error occurs in your button event set the label visibility 'true' and fill the label text with the error message.
Related
(Note: Just to clarify the problem is not specifically related to C1WebDateEdit. It could be with any custom control which require JavaScript to render actual control)
I have many C1WebDateEdit controls in my page. On a button click based on some condition I am displaying JavaScript alert message ScriptManager.RegisterStartupScript. These controls are inside UpdatePanel. The issue I am facing with it is, when these C1WebDateEdit has not value and page displays alert message, it displays "01/01/0001" behind the alert box and on closing alert it shows empty textboxes.
The reason is, C1WebDateEdit creates actual control using JavaScript. and page renders alert message JavaScript before C1WebDateEdit controls' JavaScript.
For example:
HTML markup
alert JavaScript
C1WebDateEdit JavaScript
Logical solution is get alert JavaScript after C1WebDateEdit JavaScript because it will allow C1WebDateEdit to load fully before alert box.
I found no inbuilt way in asp.net to change sequence, so I tries solution given here but It didn't work for me.
One possible solution I am thinking that I create Custom or WebUserControl and place at it last at the page in the UpdatePanel and PreRender event I call ScriptManager.RegisterStartupScript to register alert message. Logically I think it will work but trying to find that any one implemented any other solution for it?.
Other possible solution is use "pageLoaded" event of PageRequestManager. I created below function for temporary fix:
function delayedAlertBox(strMsg)
{
var fnc = function (a, b)
{
//remove reference so on next call it do not show previous alerts.
Sys.WebForms.PageRequestManager.getInstance().remove_pageLoaded(fnc);
alert(strMsg);
}
//add function reference to call on Ajax pageloaded event
Sys.WebForms.PageRequestManager.getInstance().add_pageLoaded(fnc);
}
and calling in asp.net like simple function as given below:
ScriptManager.RegisterStartupScript(Page, Page.GetType(), "dd", "delayedAlertBox('Hi, how are you?')", True)
But still looking for any other good alternative. If I found other, I will post it.
All ASP.Net client validation messages can be shown as an alert by setting the ShowMessageBox="True" property on the ValidationSummary control.
This works fine for anything that happens on the client.
For the custom validators that validate server-side I had assumed that what would happen is that when the page is returned to the browser, ASP.Net would inject some javascript to show the alert box. However this isnt the case.
If you had relied on the message box to show detail and just have a * next to the erroneous field (as per my clients req's) then it wont work as intended.
Does anyone have a solution for doing this? What I want is a way to possibly override the ValidationSummary control to inject javascript onto the page or something like this.
Thanks in advance.
You may use Page.RegisterStartupScript to show alerts after server-side validation.
I have a CustomValidator, RequiredFieldValidator and ValidationSummary controls on an aspx page to check the current password and make sure the new password is not blank.
When I click submit I get the js alert() box from the summary control telling me about just the RequiredFieldValidator being false, but the client script for the CustomValidator does not seem to get its return value used. I have checked the "arguments.IsValid" value using FireBug, so it is getting called and returning the correct bool, but it never shows up in the val summary box?
Thanks,
Goosey
Its hard to say what is going on without the code. As a side note, you might want to check out the xVal framework as I think it handles what you are looking to do.
I have an asp.net server control (with the asp: in its definition). The button has been set to do post back.
On the server side, I have the on click event handler
e.g btnSave_click()
On the client side, I have a javascript function to be invoked on the click event
e.g btnSave.Attributes.Add("onclick","javascript: return CheckIsDirty();")
Am not sure which order these two will be executed. Because I want first on the client side to warn of any data entry fields that are not yet filled-out before actually saving any data.
Any help?
First client side, second server-side.
So you can use it.
I also use it in some cases, like:
close.Attributes["OnClick"] = "return confirm('Are you sure?')";
In this case if the user presses 'No' then the server-side event handler does not even play a role.
The trick here is to set this global variable "Page_IsValid" false if your test fails and this will stop the post back.
Read this page http://msdn.microsoft.com/en-us/library/aa479045.aspx which explains both server side and client Validation. There is sone good code example you can use.
The way you are setting your onClick JavaScript event will actually prevent it from posting back as you are overwritten the ASP.NET event handler. The correct way to accomplish the validation you are intending is to:
btnSave.Attributes.Add("onclick", "CheckIsDirty();" + GetPostBackEventReference(btnSave).ToString());
Notice that you append the result of GetPostBackEventReference, so that in JavaScript you first call your CheckIsDirty() method and then call the ASP.NET postback method. Assuming your method returns true, then the button will post. If it returns false then it will not cause a post back.
Does that sound like what you are trying to accomplish?
I think you need a much better understanding of what it means client side and what it means server side and how they all relate together. I've seen more and more developers make a mess of it.
Of course the client side will execute first in your case. Actually there's no way to execute it after the server code is executed (except if you do something manually). I'll try to give a brief explanation:
Whatever you have in your server, will generate some HTML on the client and the user is always interacting on the client. So you have a html button that the user is clicking. What the browser will do is execute the javascript associated with it or if no javascript is specified and the button is a submit button it will submit the form. if you check the generated html you will see that for the onclick event you will have the script you have added followed by some autogenerated script that actually will submit the form to the server. Your server side code will execute only if the page will be submitted.
I am using the open source Javascript WYSIWYG from OpenWebWare and Asp.Net RequiredFieldValidator on the TextBox which I am calling the WYSIWYG for. Everything works fine, but the first time I try to submit the form, I get the server-side RFV ErrorMessage "Required", but if I submit a second time, it goes through.
Am I missing something? I would like to have the client-side validation... how can I get the text to register as not empty?
I think the reason for this behavior is that validation code runs earlier than the code that updates underlying TextBox from value of WYSIWYG. So the first time you get the error, then the field is updated and the second time you don't get it. Try removing all the content the second time and I bet you wont get validation error (since the value for validator at the moment is what you actually submitted the first time).
The solution would be to find a JavaScript API call for your WYSIWYG which would force the update of the underlying text box field and call it onclick (client-side) of your submit button or whatever you use for that.
the textarea HTML tag is one of the most unpleasent tags to work with and I'm not 100% sure if the client-side validator will support it, regardless of whether it's a WYSIWYG or not.
I think you'd be best off using a CustomValidator and writing the JavaScript which does the checking manually.
Alternatively you can debug though the JavaScript which is used with FireBug or VS 2008.