and thank you for reading this!
I may be looking right past the answer for this, or it may be that it was never designed to happen since ValidationSummary is client-side logic, but is there any way to retrieve the error text of a validation summary field in ASP.NET from the C# code-behind? The goal here is to construct a message that includes various information entered by the user, plus any errors that might be preventing that user from completing an operation.
It's fine if it can't be done since I am not expecting client side validation to be much of an issue for users in this program, but it would be nice to include for the sake of completion. Any advice would be appreciated.
Thank you!
Your trouble is probably that these often validate on the client side and not the server side, if they don't actually cause postback. You may be best trying to switch to a CustomValidator and do your checks there.
These happen on the server side and not the client side.
Take a look at the documentation on MSDN http://msdn.microsoft.com/en-us/library/9eee01cx(v=vs.85).aspx
I've never tried this, but here is a quick example of what may work.
Front end
<asp:TextBox id="Text1" runat="server" />
<asp:CustomValidator id="CustomValidator1" runat="server"
OnServerValidate="CustomValidator1_ServerValidate"
Display="Static"
ErrorMessage="My default message."/>
Back End
protected void ServerValidation (object source, ServerValidateEventArgs args)
{
// default to valid
args.IsValid = true;
int i;
if (int.TryParse(Text1.Text.Trim(), out i) == false)
{
// validation failed, flag invalid
args.IsValid = false;
CustomValidator1.ErrorMessage = "The value " + Text1.Text.Trim() + " is not a valid integer";
}
}
protected string GetErrors()
{
string Errors = "";
bool isValidTest = false;
Validate("myValidationGroup");
isValidTest = IsValid;
if (!isValidTest)
{
foreach (BaseValidator ctrl in this.Validators)
{
if (!ctrl.IsValid && ctrl.ValidationGroup == "myValidationGroup")
{
Errors += ctrl.ErrorMessage + "\n";
}
}
}
return Errors.Trim();
}
Related
I have to show confirmation dialogue on particular condition.And then proceed according to YES or No clicked.I tried with the following.
In aspx:
<script type="text/javascript">
function ShowConfirmation() {
if (confirm("Employee Introduced already.Continue?") == true) {
document.getElementById("hdn_empname").value = 1;
}
}
</script>
<asp:HiddenField ID="hdn_empname" runat="server" />
in cs:
if (reader2.HasRows)
{
Page.ClientScript.RegisterStartupScript(this.GetType(), "showAl", "ShowConfirmation();", true);
}
else
{
hdn_empname.Value ="1";
}
if ((hdn_empname.Value)=="1")
{
//some code to execute
}
But hdn_empname shows value="" while debuging.
Can anyone help me doing this?
Thanks in advance.
Try it
You need to ClientID
document.getElementById('<%=hdn_empname.ClientID%>').value = 1;
I found out your main problems
The hidden field values will assign after the if condition call.
Edit :
So, You need to call your logic's in javascript side using ajax
if (confirm("Employee Introduced already.Continue?") == true) {
//some code to execute
}
Where is your break point? If reader2.HasRows returns true your javascript will be registered. But it set the value on client and you get the result after postback.
hdn_empname is server controls Id which is different from client sided id, to get client sided id you need to use ClientID
try this:
document.getElementById('<%=hdn_empname.ClientID%>').value = "1";
You dont need to compare
if (confirm("Employee Introduced already.Continue?") == true)
this will work:
if (confirm("Employee Introduced already.Continue?"))
I have two Textboxes:
1. Textbox1 gets an email address (email textbox on a form)
2. Textbox two asks the user to confirm email
I need to compare the email address entered in Textboxes 1 by asking the user to re-enter in textbox 2. Then evaluate a statement and set a bool to true or false.
I read on all the Methods line String.Equals and others and tried using them.
I have these two variables in a class that I need to access in other parts on the program:
public static bool IsValidEmail { get; set; }
public static bool IsValidEmailConfirmed { get; set; }
if (!string.IsNullOrEmpty(checkEmail))
{
IsValidEmail = Regex.IsMatch(checkEmail, MatchEmailPattern);
}
else
{
IsValidEmail = false;
}
//VERIFY EMAIL ADDRESS MATCHES
//---------------------------
if (IsValidEmail == true)
{
IsValidEmailConfirmed = checkEmailConfirm.Equals(checkEmail);
}
else
{
IsValidEmailConfirmed = false;
}
The problem is I only want the confirm Textbox to request an entry if the initial Textbox pass validation. It would not make sense asking some to confirm a bad email address (format). So the user enters an email, if it fails, a confirmation is not requested, however this variable IsValidEmail = false; will evaluate to false which will indicate an error.
Finally if the first box pass validation and the confirmation fails, the error message ask for confirmation.
The code above is broken down as I have been trying to do different things.
Thanks for helping.
you don't specify if it's web forms or MVC, as MVC has a really powerful helpers for this, I'm going to assume that this is web forms.
from your code, you should refactor to:
IsValidEmail = !string.IsNullOrEmpty(checkEmail) && Regex.IsMatch(checkEmail, MatchEmailPattern);
//VERIFY EMAIL ADDRESS MATCHES
IsValidEmailConfirmed = IsValidEmail && checkEmailConfirm == checkEmail;
apart of that, I would also suggest to use jQuery Validate (assuming that you use jQuery already) and do this in the client as well.
<form ...>
Email: <input type="text" id="email" name="email" class="required email" />
Confirm email: <input type="text" id="email2" name="email2" class="required email" equalTo="#email" />
</form>
Live demo for jQuery Validate with equality among 2 fields: http://jsbin.com/imiten/1/
You could to nest the logic or change it from a property to a function.
Nest
if(validEmail)
{
if(!match)
{
'Code for non matching, flags/vars.
}
else
{
'Here is the point where all the data is validated.
}
}
else
{
'Code for invalid email, flags, variables
}
Or function
Public void validateEmail()
{
if(!validEmail)
{
'Set property
return; 'This will exit the function right here.
}
if(!matching)
{
'Set properties/vars
return; 'Another exit.
}
'If the code makes it here your data is valid
}
Here's the deal. Have a functioning web app using ASP.NET WebForms with a C# backend. The thing works fine, but I'm always looking to improve, as a beginner at this stuff. Right now, to deal with a user's search coming back with no results, I utilize the following, and was wondering if there was any cleaner way to do it, for future reference:
DataClass data = new DataClass();
var searchresults = data.GetData(searchBox.Text);
int datanumber = searchresults.Count();
if (datanumber == 0)
{
ClientScript.RegisterStartupScript(this.GetType(), "alert", "javascript:alert('There were no records found to match your search');", true);
}
else
{
DropDownList1.Visible = true;
DropDownList1.Items.Clear();
DropDownList1.DataSource = searchresults;
DropDownList1.DataBind();
}
I agree with the not using popups, so you could always do something as simple as having a Label object on your page:
<asp:Label runat="server" id="lblResultMsg" ForeColor="Red" Visible="False" />
And then set the text dynamically (or add it as a property to the code) and set the label to be visible on postback if no results are found:
if (datanumber == 0)
{
lblResultMsg.Text = "There were no records found to match your search.";
lblResultMsg.Visible = true;
}
else
{
lblResultMsg.Text = "";
lblResultMsg.Visible = false;
// do your data binding
}
But there are quite a vast number of ways you could achieve something like this. Regarding your question about using the .Count from the Enumerable collection - there's nothing stopping you doing this as it's perfectly valid. The question is which method do you find more readable?
if you include the jquery ui dialog (http://jqueryui.com/demos/dialog/), you can simply call this to create a nice dialog box:
$('<div>message</div>').dialog({autoOpen:true,title:'Error'});
Personally I prefer to create a helper function for inserting the relevant javascript into the page, and only pass parameters to the function so that I don't need to worry about the messy details every time.
Something like :
public static void GrowlMessage(System.Web.UI.Control pageControl, string header = "", string message = "", bool sticky = false, string position = "top-right", string theme = "", bool closer = true, int life = 8)
{
string _js = "$.jGrowl('" + HttpContext.Current.Server.HtmlEncode(message) + "', { header:'" + header + "', sticky:" + sticky.ToString().ToLower() + ", position: '" + position + "', theme: '" + theme + "', closer: " + closer.ToString().ToLower() + ", life:" + life * 1000 + "});";
ScriptManager.RegisterStartupScript(pageControl, pageControl.GetType(),"Growl",_js, true);
}
The sample I have used also requires jQuery and the jGrowl library available here. And IMHO the messages are pretty. They are unobtrusive, the user does not need to click a button to make them go away, and they fade away after your specified amount of time.
But I agree with Mike, that if you don't have any records, you should just use the built in properties of a GridView (EmptyDataRowStyle and EmptyDataRowText) to display a 'no data matching your query' style message. Assuming that you're using a GridView at all, that is..
When it comes to user feedback, Impromptu is my friend. There is a nice ASP.NET implementation of Impromptu on Aaron Goldenthal's website: http://www.aarongoldenthal.com/post/2009/11/11/Using-jQuery-Impromptu-With-ASPNET.aspx
If you have decided to alert user via alert then please go ahead with light box effect..
http://www.designyourway.net/blog/resources/30-efficient-jquery-lightbox-plugins/
if you are still would like to go ahead with traditional alert then obviously its easy for you to fire it up on page load rather than attaching script to it..
')" ....>
Because if you require any change then you just need to alter the javascript alone and you dont need to build project again to test it...
Hope its useful for you..
Note: I'm using my own DLLs to render content so above coding may requires alteration because i did forget traditional asp codings.. :)
Hi i have the following pagemethod, however it dues not seem to be working, i tried debugging it and it does not hit the method. Here is what my method looks like;
function InsertStatus() {
var fStatus = document.getElementById('<%=txtStatus.ClientID %>').value;
PageMethods.InsertStatusUpdate(fStatus, onSucess, onError);
function onSucess(result) {
alert(result);
}
function onError(result) {
alert('Cannot process your request at the moment, please try later.');
}
}
And my codebehind;
[WebMethod]
public static string InsertStatusUpdate(string fStatus)
{
string Result = "";
int intUserID = -1;
if (String.IsNullOrEmpty(HttpContext.Current.User.Identity.Name))
HttpContext.Current.Response.Redirect("/login");
else
intUserID = Convert.ToInt32(HttpContext.Current.User.Identity.Name);
if (string.IsNullOrEmpty(fStatus))
return Result = "Please enter a status";
else
{
//send data back to database
return Result = "Done";
}
}
When i click my button it goes straight through the onError Method. Can anyone see what i am doing wrong?
I found the problem i needed a [System.Web.Script.Services.ScriptService] above the method, due to the fact it is being called by a script. Thanks for all the suggestions.
If I were to guess, I would focus on this:
intUserID = Convert.ToInt32(HttpContext.Current.User.Identity.Name);
The best way to solve this is set a breakpoint and start walking through the code. When you run a line and are redirected to the error page, you have found your problem.
The reason I picked that line, is the user is a string. Now, it may be your users are numbers, but it could also be including a domain user == "mydomain/12345", which is not an integer, even if the user part of the string is.
As far as I know, you can't Response.Redirect in a PageMethod.
Return a string of the redirect URL and then use JavaScript document.location.href to handle the redirection.
EDIT: I've just seen that you tried debugging and the method isn't hit: ensure your ScriptManager has EnablePageMethods set to true:
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true"/>
I have a gridview with three columns of textboxes. It can have as many rows as necessary but its usually only about 5 rows. Each row needs to be validated.
I want to create a client side validator that sums 2 of the columns together and compares it with the third column to check that the user has entered the data correctly.
Just in case you are wondering, it's part of the spec that the operator must enter the third column rather than simply summing the two previous columns together in the code behind. This is done to ensure the operator is transcribing the information correctly.
I am trying to use the custom validator in .net to create this client side validation. but I can't find a way to pass to it the names of the three text boxes.
I can give it the target controls name using the ControlToValidate parameter, but how do I pass in the other two control id's ?
I am looking for the 'proper' way to do this, one thought is to create an array in javascript referenced by the controltovalidate's name.
DC
I solved the problem. not an elegant solution but it works.
first I placed the code into a div on the page
<div align="right"><asp:CustomValidator ID="RowValidator" runat="server"
ErrorMessage="Total of #total# does not equal 1st Preference + Ticket"
ControlToValidate="Total" ValidateEmptyText="True"
ClientValidationFunction="CheckRow" SetFocusOnError="True" EnableClientScript="True"
enableViewState="False" Display="Dynamic"></asp:CustomValidator></div>
Then I created a JavaScript function...
function CheckRow(sender,args) {
// get the name of the control to validate
try {
args.IsValid = true;
ctv = sender.controltovalidate;
// get the data from the other controls
nt = document.getElementById(ctv.replace('_Total','_NonTicket'));
t = document.getElementById(ctv.replace('_Total','_Ticket'));
if (nt && t) {
v1 = Number(nt.value);
v2 = Number(t.value);
v3 = Number(args.Value);
if ((v1 + v2) != v3){
msg = GetMessage(sender);
sender.innerHTML = msg.replace("#total#",Number(args.Value));
args.IsValid = false;
return false;
}
}
}
catch (e) {
// something wrong default to server side validation
}
return true;
}
This is called by the custom validator for each row I use the controltovalidate parameter of the sender to get the name
then its a matter of a bit of string manipulation to get the names of the other fields.
Once retrieved you can do what you like, in my case I add and compare. if there is an error the Isvalid flag is cleared and the message is modified to suit.
The getmessage function is required because I alter the message to give a more meaningful error message
/*
get the error message from the validator
store it so it can be retrieved again
this is done because the message is altered
*/
function GetMessage(sender){
msg = window[sender.id+"_msg"];
if (!msg){
msg = sender.innerHTML;
window[sender.id+"_msg"] = msg;
}
return msg;
}
The getmessage function keeps a copy of the original message so if the user makes a mistake more than once the message can be retrieved in its pristine form, other wise the first time we edit a message we overwrite the placeholder (#total#).
DC