Custom control doesn't fire validation
I've written a custom ASP.net control that descends from LinkButton and overrides the Render() method. I'm using it to replace ImageButtons in the site I'm working on so we don't have to have an image for each button.
This control works fine, does the required post-backs etc., however it doesn't fire the validators in its validation group. This is obviously an issue.
The code for the control is (condensed) as follows:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public class CustomButton : LinkButton
{
public string SpanCssClass { get; set; }
protected override void Render(HtmlTextWriter writer)
{
if (!Visible)
{
return;
}
writer.AddAttribute(HtmlTextWriterAt开发者_如何学编程tribute.Name, UniqueID);
writer.AddAttribute(HtmlTextWriterAttribute.Id, ClientID);
writer.AddAttribute(HtmlTextWriterAttribute.Class, CssClass);
string postback = string.IsNullOrEmpty(OnClientClick) ? "javascript:__doPostBack('" + UniqueID + "','');" : OnClientClick;
writer.AddAttribute(HtmlTextWriterAttribute.Href, postback);
writer.RenderBeginTag(HtmlTextWriterTag.A);
writer.AddAttribute(HtmlTextWriterAttribute.Class, SpanCssClass);
writer.RenderBeginTag(HtmlTextWriterTag.Span);
writer.Write(Text);
writer.RenderEndTag();
writer.RenderEndTag();
}
}
Does anyone know why this would not be causing the validators to fire?
I was under the impression that leaving all the other methods in LinkButton un-overridden would leave all the other functionality the same!
Problem is you're generating your own script, allow asp.net to do it for you and it should work better. Something like this will work better.
PostBackOptions options = new PostBackOptions(this);
options.PerformValidation = true;
options.RequiresJavaScriptProtocol = true;
string postback = string.IsNullOrEmpty(OnClientClick) ? this.Page.ClientScript.GetPostBackEventReference(options) : OnClientClick;
Well, if you want to trigger validation manually if CausesValidation is true, you can call Page_Validate client-side method to trigger the validation. I think it takes one param, the validation group, to validate...
HTH.
精彩评论