关于为DetailsView控件添加客户端验证

 在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);
        }

    }

 其中有一些异常的行为,表现在这里

string clientID=cell.Controls[0].ClientID; 

如果不加上这句话,DetailsView在呈现时,默认生成的 input控件只有name属性,而没有id属性,而asp.net的客户端页面验证需要控件具有id值才能正确运行;加上这句话,DetailsView生成的input就带有id属性了,不过这个行为我感觉很奇怪,不知道有哪位高人能说出其中道理。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值