在msdn杂志上搜到,为DetailsView控件添加客户端验证的方式至少有2种
1:通过Template 方式,为模版中的控件添加。我认为这种方式容易把前台html声明弄得非常混乱。
2:通过后台代码动态添加控件,msdn杂志上为vb代码,我把它变成了c#代码,如下所示,代码中有一处行为比较怪异,下文将提到:
protected
void
DetailsView1_ItemCreated(
object
sender, EventArgs e)
... {
if(DetailsView1.CurrentMode==DetailsViewMode.ReadOnly)return;
AddRequiredFieldValidator(1, "请填写用户名");
AddRequiredFieldValidator(2, "请填写用户密码");
AddRequiredFieldValidator(3, "请填写电子邮件");
}
private void AddRequiredFieldValidator( int rowIndex, string msg)
... {
const int DataCellIndex = 1;
DetailsViewRow row = DetailsView1.Rows[rowIndex];
DataControlFieldCell cell = row.Cells[DataCellIndex] as DataControlFieldCell;
RequiredFieldValidator req=new RequiredFieldValidator();
req.Text = String.Format("<span title='{0}'>***</span>", msg);
string ctlID = cell.Controls[0].UniqueID;
//((WebControl)cell.Controls[0]).Attributes.Add("id", cell.Controls[0].ClientID);
string clientID=cell.Controls[0].ClientID; //must useit here or it won't appear on the client
int pos = ctlID.LastIndexOf("$");
if (pos > 0)
...{
req.ControlToValidate = ctlID.Substring((pos + 1));
cell.Controls.Add(req);
}
}
... {
if(DetailsView1.CurrentMode==DetailsViewMode.ReadOnly)return;
AddRequiredFieldValidator(1, "请填写用户名");
AddRequiredFieldValidator(2, "请填写用户密码");
AddRequiredFieldValidator(3, "请填写电子邮件");
}
private void AddRequiredFieldValidator( int rowIndex, string msg)
... {
const int DataCellIndex = 1;
DetailsViewRow row = DetailsView1.Rows[rowIndex];
DataControlFieldCell cell = row.Cells[DataCellIndex] as DataControlFieldCell;
RequiredFieldValidator req=new RequiredFieldValidator();
req.Text = String.Format("<span title='{0}'>***</span>", msg);
string ctlID = cell.Controls[0].UniqueID;
//((WebControl)cell.Controls[0]).Attributes.Add("id", cell.Controls[0].ClientID);
string clientID=cell.Controls[0].ClientID; //must useit here or it won't appear on the client
int pos = ctlID.LastIndexOf("$");
if (pos > 0)
...{
req.ControlToValidate = ctlID.Substring((pos + 1));
cell.Controls.Add(req);
}
}
其中有一些异常的行为,表现在这里
string clientID=cell.Controls[0].ClientID;
如果不加上这句话,DetailsView在呈现时,默认生成的 input控件只有name属性,而没有id属性,而asp.net的客户端页面验证需要控件具有id值才能正确运行;加上这句话,DetailsView生成的input就带有id属性了,不过这个行为我感觉很奇怪,不知道有哪位高人能说出其中道理。