I have created a custom server control. So far this control renders some html in the webpage. On submit of the page i need to take the values entered in the textbox of the server control and call some webservice to validate the input of the user. i don't want to write this code in code behind of the page that this control is used in. I want all the validations to be written in the server control itself and if validation fails, Page.IsValid should be set to false. If the user input value in server control is valid Page.IsValid will be true.
I am trying to achieve is the same functionality as google recaptcha. All user needs to do to use this control is to user the开发者_如何学C control in the page. user entered value is correct or incorrect is handled in the control itself and in the code behind of the page, there is only Page.IsValid. Here is the page on google that explains this
http://code.google.com/apis/recaptcha/docs/aspnet.html
and i have also used the google recaptcha and it works as expected. I also want to build same kind of functionality for my server control, Please help, if it is possible.
Thank's for answering the questions. I found the solution. Here is the entire code of the server control. The trick was to implement IValidator. It gives us two property and one metod. ErrorMessage and IsValid properties and Validate method. I wrote all the validation code in Validate method and set this.IsValid. This solved the problem.
[ToolboxData("<{0}:MyControl runat=server></{0}:MyControl>")]
public class MyControl : WebControl, IValidator
{
protected override void RenderContents(HtmlTextWriter output)
{
//Render the required html
}
protected override void Render(HtmlTextWriter writer)
{
this.RenderContents(writer);
}
protected override void OnInit(EventArgs e)
{
Page.Validators.Add(this);
base.OnInit(e);
}
public string ErrorMessage
{
get;
set;
}
public bool IsValid
{
get;
set;
}
public void Validate()
{
string code = Context.Request["txtCode"];
this.IsValid = Validate(code);//this method calls the webservice and returns true or false
if (!this.IsValid)
{
ErrorMessage = "Invalid Code";
}
}
}
You could incorporate the validator in the server control. It would need a server validate method to call the web service.
The net result would be a server control that you drop on the page, no other validators needed. if your control can't validate it's contents, then page.isvalid will be false.
Simon
精彩评论