I am using Uploadify v2.1.4 to upload images using ASP.Net C# FM 4.0.
In this page i have other controls also, but i want a functionality in such a way that when i upload images it should automatically refresh the UpdatePanel1 to show image uploaded
Default.aspx FILE
<asp:UpdatePanel ID="UpdatePanel1" runat="server" >
<ContentTemplate>
<asp:DataList ID="DataList1" runat="server" DataSourceID="SqlDataSource1" RepeatDirection="Horizontal" >
<ItemTemplate>
<br /><img src='http://test.kashmirsouq.com/ImageUploads/<%# Eval("ImageID") %>' width="100px" height="100px" vspace="2" hspace="2" border="1" />
<br /><asp:LinkButton ID="lnkBtnDeleteImage" CommandArgument='<%# Eval("sno") %>' CommandName="Delete" runat="server">
Delete</asp:LinkButton>
<br />
</ItemTemplate>
</asp:DataList>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:SQLConnectionString %>"
SelectCommand="SELECT [sno], [ImageID] FROM [User_Images]">
</asp:SqlDataSource>
</ContentTemplate>
</asp:UpdatePanel>
Page example is here test.kashmirSouq.com
I am calling FileUplaad.aspx file to upload image using jQuery
<script type="text/javascript">
$(document).ready(function () {
$('#fuFiles').uploadify({
'uploader': 'Scripts/uploadify.swf',
'script': 'FileUploads.aspx',
'cancelImg': 'Scripts/cancel.png',
'auto': 'true',
'multi': 'true',
'fileExt': '*.jpg;*.gif;*.png',
'buttonText': 'Browse...',
'queueSizeLimit': 5,
'simUploadLimit': 2
});
});
</script>
and in FileUpload.aspx.cs file i save the file on the server and database,
I need a way so that i can refresh the updatepanel1 from function saveData() which is in FileUpload.aspx.cs
protected int saveData()
{
String strSql = "INSERT INTO HMS_User_Images(ImageID,UserID,ImageCreationDate) ";
strSql += " VALUES ('" + filename + "','123456789', '" + DateTime.Now + "')";
int result = DataProvider.intConnect_Select(strSql);
}
So when i upload images it should refresh do partial page update of the grid. Please give me a example how i can do it using C#
Please advice how i can do this code sample would be highly appreciated.
Regards
If You want to refresh the Update panel , Try This...
UpdatePanel1.Update();
If the page is enabled for partial-page rendering, when you invoke the
Update method, the UpdatePanel control's content is updated in the
browser. Call the Update method if you have server code that must
execute to determine whether an UpdatePanel control should be updated.
If you plan to use the Update method, set the UpdateMode property to
Conditional. If you want the decision to update the panel to be
determined in server logic, make sure that the ChildrenAsTriggers
property is false and that no explicit triggers are defined for the
panel.
In a typical page development scenario, if you define triggers or if
the ChildrenAsTriggers property is true for the UpdatePanel control,
the Update method is automatically called during the page life cycle.
If the ContentTemplate property is not defined for the UpdatePanel
control, no updates of the panel will occur.
Try by showing the image by using the response after the Onupload complete event.So when the user as soon as he uploads you will find the image.
This is the script:
<script type="text/javascript">
$(window).load(
function () {
$("#fileInput1").uploadify({
'uploader': 'scripts/uploadify.swf',
'cancelImg': 'images/cancel.png',
'buttonText': 'Browse Files',
'script': 'Upload.aspx',
'folder': 'uploads',
'fileDesc': 'Image Files',
'fileExt': '*.jpg;*.jpeg;*.gif;*.png',
'queueSizeLimit': 9999,
'simUploadLimit': 2,
'sizeLimit': 4000000,
'multi': true,
'auto': true,
'onComplete': function (event, queueID, fileObj, response, data) {
$("#thumbnail").append(response)
},
'onError': function (event, ID, fileObj, errorObj) {
alert(errorObj.type + ' Error: ' + errorObj.info);
}
});
}
);
</script>
This is the Handler:
<%# WebHandler Language="VB" Class="UploadVB" %>
Imports System
Imports System.Web
Imports System.IO
Imports System.Drawing
Public Class UploadVB : Implements IHttpHandler
Public Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest
Dim postedFile As HttpPostedFile = context.Request.Files("Filedata")
Dim savepath As String = ""
Dim tempPath As String = ""
tempPath = System.Configuration.ConfigurationManager.AppSettings("FolderPath")
savepath = context.Server.MapPath(tempPath)
Dim filename As String = postedFile.FileName
If Not Directory.Exists(savepath) Then
Directory.CreateDirectory(savepath)
End If
If Not Directory.Exists(savepath + "\thumbs") Then
Directory.CreateDirectory(savepath + "\thumbs")
End If
postedFile.SaveAs((savepath & "\") + filename)
Dim fullImage As System.Drawing.Image = New System.Drawing.Bitmap((savepath & "\") + filename)
Dim newWidth As Integer = 100
Dim newHeight As Integer = 80
Dim temp As New Bitmap(newWidth, newHeight)
Dim newImage As Graphics = Graphics.FromImage(temp)
newImage.DrawImage(fullImage, 0, 0, newWidth, newHeight)
temp.Save((savepath + "\thumbs" & "\") + "t_" + filename)
context.Response.Write("<a href='" + (tempPath & "/") + filename + "'><img src='" + tempPath + "/thumbs" & "/" + "t_" + filename + "'/></a>")
context.Response.StatusCode = 200
'context.Response.Write("OK")
End Sub
Public ReadOnly Property IsReusable() As Boolean Implements IHttpHandler.IsReusable
Get
Return False
End Get
End Property
End Class
In the above code you can find thumbnails appended as soon as the user uploads you find a thumbnail of the image.
Related
I'm using webcam.js to get photos from a webcam using asp.net web form app. The problem is, I want to get the filename based on the "ID" querystring. But everytime I click "shoot" button, the querystring value is nothing.
Here's my complete HTML :
<%# Page Language="vb" AutoEventWireup="false" CodeBehind="Coba.aspx.vb" Inherits="myWebcam.Coba" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script src='<%=ResolveUrl("~/Plugin/jquery.webcam.js")%>' type="text/javascript"></script>
<script type="text/javascript">
var pageUrl = '<%=ResolveUrl("~/Coba.aspx")%>';
$(function (){
$("#Camera").webcam({
width: 320,
height: 240,
mode: "save",
swffile: '<%=ResolveUrl("Plugin/jscam.swf")%>',
onTick: function () { },
onSave: function () {
},
onCapture: function () {
webcam.save(pageUrl);
},
debug: function () { },
onLoad: function () { }
});
});
function Capture() {
webcam.capture();
return false;
};
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<h2>Index</h2>
<input type="button" value="Shoot!" onclick="Capture()" />
<div id="Camera"></div>
</div>
</form>
</body>
</html>
And here is my asp.net codebehind :
Imports System.IO
Imports System.Web.Services
Public Class Coba
Inherits System.Web.UI.Page
Public sID As String
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
sID = Request.QueryString("id")
If Not Page.IsPostBack Then
Capture(Trim(sID))
End If
End Sub
Public Sub Capture(ByVal mID As String)
Dim stream = Request.InputStream
Dim dump As String
If stream.Length > 0 Then
Using reader = New StreamReader(stream)
dump = reader.ReadToEnd()
End Using
Dim path = Server.MapPath("~/" & Trim(mID) & ".jpg")
System.IO.File.WriteAllBytes(path, String_To_Bytes2(dump))
End If
End Sub
Private Function String_To_Bytes2(strInput As String) As Byte()
Dim numBytes As Integer = (strInput.Length) / 2
Dim bytes As Byte() = New Byte(numBytes - 1) {}
For x As Integer = 0 To numBytes - 1
bytes(x) = Convert.ToByte(strInput.Substring(x * 2, 2), 16)
Next
Return bytes
End Function
End Class
The first time I run the page, I can get the "id" value from the querystring. The shoot button trigger the postback and run the "Capture" sub but the "id" querystring returns nothing.
Any solutions for this problem ?
I tried the code and I think there is a mistake concept. The plugin does not seem to append any QueryString. Your ID is always Nothing. I made debugging and found no trace of the addition ID in the QueryString.
The file name is an attribute that you assign yourself with your logic.
Here is a complete example in which the ID is not recovered.
Even in the official page of the plugin there is no reference to the ID through Querystring.
Other things, you should not use the same page for the interface and saving process. The Pageload is always called, and you call Capture(Trim(sID)) even when loads the interface.
I think you must change this line:
var pageUrl = '<%=ResolveUrl("~/Coba.aspx")%>';
In
var pageUrl = '<%=ResolveUrl("~/Coba_SaveImage.aspx")%>';
And all your codebehind go in the page Coba_SaveImage.aspx. In Page Load is not necessary the If Not Page.IsPostBack Then is always a postback.
Hope this help you.
Im trying to use an asp:progress so when I click on my asp:button it calls an ashx file which write a CSV response.
So far when I click on the button, the animation shows properly and the download start. However I can't seem to stop the animation when the file start downloading (when I get the response from the ashx file).
Here is the aspx :
<asp:Content ID="Content2" ContentPlaceHolderID="MainPlaceHolder" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server" />
<asp:UpdatePanel ID="UpdatePanel1" UpdateMode="Conditional" runat="server">
<ContentTemplate>
<p>Download a CSV file</p>
<asp:Button ID="Button2" runat="server" Text="Download"
CausesValidation="False" onclick="Button2_Click" />
</ContentTemplate>
</asp:UpdatePanel>
<asp:UpdateProgress ID="UpdateProgress1" AssociatedUpdatePanelID="UpdatePanel1" runat="server">
<ProgressTemplate>
<div id="AlertDiv" style="background:White">
<asp:Image ID="imgLoading" runat="server" ImageUrl="css/smoothness/images/animated-overlay.gif" Width="34px" />Loading...
</div>
</ProgressTemplate>
</asp:UpdateProgress>
</asp:Content>
Here is the Button2_click function :
protected void Button2_Click(object sender, EventArgs e)
{
try
{
Response.Redirect("ProductsHierarchyDownload.ashx");
}
catch (Exception ex)
{
//log
}
}
And here is the ProcessRequest function from the ashx file :
public void ProcessRequest(HttpContext context)
{
string attachment = String.Format("attachment; filename=Hierarchie des produits au {0}.csv", DateTime.Today.ToShortDateString());
context.Response.AddHeader("content-disposition", attachment);
context.Response.ContentType = "text/csv";
context.Response.AddHeader("Pragma", "public");
context.Response.ContentEncoding = Encoding.GetEncoding(1252);
context.Response.Write(DemandeTarifImageBLL.DataTableToCSVString());
}
I've tried to use javascript and the property endRequest, beginRequest and initializeRequest event of the PageRequestManager Class (I found some conde snippet here) but nothing has worked for me so far.
How do I force the animation to stop when the download starts ?
Although I was not able to try and see if its working but by my previous experience I can suggest the following. Try changing your code as follows:
public void ProcessRequest(HttpContext context)
{
string attachment = String.Format("attachment; filename=Hierarchie des produits au {0}.csv",
DateTime.Today.ToShortDateString());
context.Response.AddHeader("content-disposition", attachment);
context.Response.ContentType = "text/csv";
context.Response.AddHeader("Pragma", "public");
context.Response.ContentEncoding = Encoding.GetEncoding(1252);
context.Response.Write(DemandeTarifImageBLL.DataTableToCSVString());
context.Response.Flush();
context.Response.End();
}
Adding Flush and End clears the buffer and marks the response end respectively. This way the client would reach a definite conclusion that the Request has been completely processed.
Also you can control the update progress with the client side script, here is a sample code:
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_endRequest(EndRequest);
function EndRequest(sender, args) {
if (postBackElement.id == 'Panel1Trigger') {
$get('UpdateProgress1').style.display = 'none';
}
}
The above js code adds an handler for update panels end request event and on the function closes the Update progress.
Try putting the contents of you ProcessRequest function of your handeler to the button click event, and do remember to add Flush() and End function for the response.
EDIT 1:
On looking further in stack overflow I found the following link with the issue similar to yours, and this confirmed my assumption that you can not have a redirect inside an update panel:
asp:UpdateProgress never goes away after clicking on downloadable content inside a repeater
Hope this helps.
Try redirect to ashx from javascript.
ScriptManager.RegisterClientScriptBlock(this, typeof(Page), "downloadFileExport", "javascript:window.location ='" + ResolveUrl(downloadUrl) + "';", true)
This was solved my issue too.
In my ASP.Net Web Forms application the progress text kept showing even after the process was done. I was able to fix that in Dev environment by increasing the timeout in the ScriptManager. Example below.
I have a querystring on page load that I use to get the filename and thumbnail image for JWPlayer. It is not getting the filename or thumbname, however. There must be a reason why I can't get it over to my aspx page, from the VB code behind.See code:
Code Behind (VB):
Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load
Dim videoName As String = Request.QueryString("FileName")
Dim thumb As String = Request.QueryString("Thumb")
End Sub
And now I need to get these string variables into the .ASPX page to the JWplayer script, but they do not
.ASPX:
<div id='container'></div>
<script type="text/javascript" src="~/player/jwplayer.js</script>
<script type="text/javascript">
jwplayer("container").setup({
file: videoName,
flashplayer: '~/player/player.swf',
volume: 35,
width: 480,
height: 270,
skin: '~/player/skins/skin.zip',
image: thumb,
})
</script>
This is ho I solved it
Code Behind (VB):
Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load
Dim videoName As String = Request.QueryString("FileName")
Dim thumb As String = Request.QueryString("Thumb")
Dim dur As String = Request.QueryString("Duration").ToString()
txt1.Text = "~contents/published/" & videoName.ToString()
txt2.Text = "~/contents/thumbs/" & thumb.ToString()
txt3.Text = dur.ToString()
End Sub
Now to get the value of the query string to the JWPlayer javascript, I had to add a javascript function inside the JW script and I called it codeAddress(). This kind of documentation is NOT found on the LongTail website or tutorials or anywhere else on the internet that I have found.
.ASPX:
<script type="text/javascript">
function codeAddress() {
var dootoo = document.getElementById('<%=txt1.ClientID%>').value;
var doothree = document.getElementById('<%=txt2.ClientID%>').value;
var doofour = document.getElementById('<%=txt3.ClientID%>').value;
jwplayer("container").setup({
duration: doofour,
file: dootoo,
flashplayer: '~/player/player.swf',
skin: "~/player/skins/newtubedark.zip",
volume: 35,
width: 685,
height: 385,
image: doothree,
})
}
window.onload = codeAddress;
</script>
<asp:textbox id="txt1" runat="server" style="display:none;"></asp:textbox>
<asp:textbox id="txt2" runat="server" style="display:none;"></asp:textbox>
<asp:textbox id="txt3" runat="server" style="display:none;"></asp:textbox>
I have seen a couple of other posts on here regarding the use of Recaptcha with ASP.net UpdatePanels but have not yet found an answer that solves my problem.
Here is my ASPX code :
<asp:UpdatePanel ID="updRecaptcha" runat="server" UpdateMode="Always">
<ContentTemplate>
<recaptcha:RecaptchaControl ID="btnrecaptcha" runat="server" Theme="clean" PrivateKey"<%$ Resources: General, CaptchaPrivateKey %>" PublicKey="<%$ Resources: General, CaptchaPublicKey %>" />
<asp:Label ID="recaptchaerror" runat="server" style="color: Red;"/>
</ContentTemplate>
</asp:UpdatePanel>
So the Recaptcha control lives within a user control that uses several .Net validation controls (e.g. RequiredFieldValidator). I need to valdiate the Recaptcha and the ASP.net controls before allowing the process to continue.
If any of the validation fails (Recaptcha or .Net) then the Recaptcha control disappears. Looking at the HTML source, the control isn't loading at all after the Postback - eventhough I am telling the UpdatePanel to update.
I can't reload the page completely as this all appears as an overlay on top of the page and there are other form fields on the page behind.
Please help!
Edit:
From C# when the Recaptcha fails I am calling this code :
ScriptManager.RegisterClientScriptBlock(Page, Page.GetType(), "InvalidRecaptcha", "alert('Recaptcha Failed');Recaptcha.reload();alert('Recaptcha Reloaded');", true);
Both of the alert statements fire but the Recaptcha still does not load.
The accepted solution did not work for me. Here is the answer that I have tried and is working:
ASP.Net, disappearing Recaptcha, UpdatePanels and Partial PostBacks: Fixed once and for all
Basically it involves creating a hidden div and using jquery to re-render the html. Also the blog post gives a nice little breakdown of the typical solutions (e.g., using RegisterClientScriptBlock with a simple reload) and why they fail.
<div runat="server" id="pbTarget" visible="false"></div>
<recaptcha:RecaptchaControl ID="recaptcha" runat="server" Theme="clean" />
code behind:
protected void btnSubmit_Click(object sender, EventArgs e)
{
recaptcha.Validate();
if (!Page.IsValid || !recaptcha.IsValid)
{
pbTarget.Visible = true;
ScriptManager.RegisterClientScriptBlock(
recaptcha,
recaptcha.GetType(),
"recaptcha",
"Recaptcha._init_options(RecaptchaOptions);"
+ "if ( RecaptchaOptions && \"custom\" == RecaptchaOptions.theme )"
+ "{"
+ " if ( RecaptchaOptions.custom_theme_widget )"
+ " {"
+ " Recaptcha.widget = Recaptcha.$(RecaptchaOptions.custom_theme_widget);"
+ " Recaptcha.challenge_callback();"
+ " }"
+ "} else {"
+ " if ( Recaptcha.widget == null || !document.getElementById(\"recaptcha_widget_div\") )"
+ " {"
+ " jQuery(\"#" + pbTarget.ClientID + "\").html('<div id=\"recaptcha_widget_div\" style=\"display:none\"></div>');"
+ " Recaptcha.widget = Recaptcha.$(\"recaptcha_widget_div\");"
+ " }"
+ " Recaptcha.reload();"
+ " Recaptcha.challenge_callback();"
+ "}",
true
);
return;
}
else
{
//normal page processing here...
If you are using Recaptcha 2.0 this is your Javascript
<script type="text/javascript">
function CaptchaReload() {
Recaptcha.create("yourpublicKey", 'yourRecaptchadiv', {
theme: 'white',
callback: grecaptcha.reset()
});
}
This is your recaptcha Div
<div class="g-recaptcha" data-sitekey="yourPublicKey"></div>
Then at end of postback event call the Javascript
protected void txtEmail_TextChanged(object sender, EventArgs e)
{
if (txtEmail.Text != string.Empty)
{
ValidateEmail();
ScriptManager.RegisterStartupScript(this, this.GetType(), "CaptchaReload", "$.getScript(\"https://www.google.com/recaptcha/api.js\", function () {});", true);
}
}
Forget the ScriptManager. All you need is this script in the page. Change accordingly for your identifiers:
<script type="text/javascript">
// RECAPTURE CODE FOR RELOADING AFTER INCORRECT ENTRY
if (typeof Sys != 'undefined') {
var requestManager = Sys.WebForms.PageRequestManager.getInstance();
requestManager.add_endRequest(function(sender, args) {
$('<div id="recaptcha_widget_div"/>').appendTo('#recaptcha_widget_div2');
if (typeof Recaptcha != 'undefined') {
Recaptcha.create(recaptcha_key, "recaptcha_widget_div",
{
theme: "red",
callback: Recaptcha.focus_response_field
});
}
});
}
Surprisingly, I didn't need to apply the RegisterClientScriptBlock call to make it work.
I just use:
UpdateMode="Always"
for the updatepanel and on the server side I call:
updatePanel.Update();
This also prevents the captcha from displaying a new challenge.
My answer is basically the same as "User" (that worked !), but to help anyone using VB.
I would have commented there, but I have zippo rep...
(hope this isn't too much of an infraction, and that it helps someone out)
I ported the meat of this to VB.NET:
pbTarget.Visible = True
Dim _sb As New StringBuilder
With _sb
.Append("Recaptcha._init_options(RecaptchaOptions);")
.Append("if ( RecaptchaOptions && ""custom"" == RecaptchaOptions.theme )")
.Append("{")
.Append(" if ( RecaptchaOptions.custom_theme_widget )")
.Append(" {")
.Append(" Recaptcha.widget = Recaptcha.$(RecaptchaOptions.custom_theme_widget);")
.Append(" Recaptcha.challenge_callback();")
.Append(" }")
.Append("} else {")
.Append(" if ( Recaptcha.widget == null || !document.getElementById(""recaptcha_widget_div"") )")
.Append(" {")
.Append(" jQuery(""#")
.Append(pbTarget.ClientID)
.Append(""").html('<div id=""recaptcha_widget_div"" style=""display:none""></div>');")
.Append(" Recaptcha.widget = Recaptcha.$(""recaptcha_widget_div"");")
.Append(" }")
.Append(" Recaptcha.reload();")
.Append(" Recaptcha.challenge_callback();")
.Append("}")
End With
ScriptManager.RegisterClientScriptBlock(recaptcha, recaptcha.[GetType](), "recaptcha", _sb.ToString, True)
I was able to make it work using version 2.1.0.0 of the reCAPTCHA library for .NET with webforms, script manager and inside an update panel.
First, in the .aspx page outside of the update panel I'm loading the Google reCAPTCHA library:
<script src="https://www.google.com/recaptcha/api.js?onload=onloadCallback&render=explicit"
async defer></script>
Second, in the .aspx page inside the update panel I added a div that will work as the target panel to load the reCAPTCHA:
<div runat="server" id="pbTarget" visible="false"></div>
<cc1:Recaptcha ID="recaptcha" runat="server" Theme="Clean" />
Third, in the code behind at the end of my postback event I registered a startup script to render the reCAPTCHA in my target panel
Private Sub cmdSubmit_Click(sender As Object, e As EventArgs) Handles cmdSubmit.Click
pbTarget.Visible = True
ScriptManager.RegisterStartupScript(
UpdatePanel1,
UpdatePanel1.GetType(),
"loadCaptcha",
"grecaptcha.render('" & pbTarget.ClientID & "', {'sitekey': 'YourKey' });",
End Sub
You need to reload reCaptcha control with javascript, try this:
protected void Button1_Click(object sender, EventArgs e)
{
btnrecaptcha.Validate();
if(IsValid && updRecaptcha.IsValid}
{
//Some logic here
}
ScriptManager.RegisterClientScriptBlock(Page, Page.GetType(), "CaptchaReload", "Recaptcha.reload();", true);
}
is it possible to use javascript so that when an asp.net validator fails (for example the input doesnt match the regex), the textbox border and background color changes to a shade of red. Iv seen this before, but i forgot where.
Can someone please link me to a live example of such?
And a way i can do this?
Thanks
Edit:
Using this solution:
validateField = function(sender, args){
//do your validation logic
if (!args.IsValid){
var ctrl = $("#" + sender.controltovalidate);
if (ctrl){
ctrl.css({ "background-color" : "#990000", "border" : "1px solid #993300" });
}
}
return args.IsValid;
}
If i where to use regular exressions, is this the correct way to do it?
validateField = function(sender, args){
var regEx=(some regex forumla)
if (sender.value.search(regEx)==-1)
var ctrl = $("#" + sender.controltovalidate);
if (ctrl){
ctrl.css({ "background-color" : "#990000", "border" : "1px solid #993300" });
}
}
else
{
return args.IsValid;
}
}
Sorry for my lack of knowledge, iv never used javascript before. Also, what is the:
return args.IsValid;
At the end for?
You can use a CustomValidator, and if validation fails you can change the border and background colors in the client-side validation function:
Validation function:
validateField = function(sender, args){
//do your validation logic
if (!args.IsValid){
var ctrl = $("#" + sender.controltovalidate);
if (ctrl){
ctrl.css({ "background-color" : "#990000", "border" : "1px solid #993300" });
}
}
return args.IsValid;
}
Markup:
<asp:TextBox ID="TextBox1" runat="server" />
<asp:CustomValidator ID="CustomValidator1" runat="server" EnableClientScript="true"
ErrorMessage="Required"
ClientValidationFunction="validateField"
ControlToValidate="TextBox1"
Display="Dynamic">
</asp:CustomValidator>
I have done something like this
Private Sub HighlightInvalidFields()
For Each validator As IValidator In Page.Validators
If TypeOf validator Is BaseValidator Then
If CType(validator, BaseValidator).IsValid = False Then
Dim controlId As String = CType(validator, BaseValidator).ControlToValidate
Dim control As WebControl = TryCast(Me.FindControlRecursive(controlId), WebControl)
If control IsNot Nothing Then
control.Style.Add("background-color", "#B85449")
End If
End If
End If
Next
End Sub
I call it from the page_prerender
Private Sub Page_PreRender(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.PreRender
If Page.IsPostBack Then HighlightInvalidFields()
End Sub
public class ChangeColorPage : Page {
public Label lblZip;
public RegularExpressionValidator valZip;
protected override void OnLoad(EventArgs e) {
Page.Validate();
lblZip.ForeColor = valZip.IsValid? Color.Black : Color.Red;
}
}
<asp:Label id=lblZip runat=server Text="Zip Code:"/>
<asp:TextBox id=txtZip runat=server OnChange="txtZipOnChange();" /></asp:TextBox><br>
<asp:RegularExpressionValidator id=valZip runat=server ControlToValidate=txtZip ErrorMessage="Invalid Zip Code" ValidationExpression="[0-9]{5}" /><br>
<script language=javascript>
function txtZipOnChange() {
// Do nothing if client validation is not active
if (typeof(Page_Validators) == "undefined") return;
// Change the color of the label
lblZip.style.color = valZip.isvalid ? "Black" : "Red";
}
</script>
http://msdn.microsoft.com/en-us/library/aa479045.aspx