我创建了一个具有一些自定义客户端验证的用户控件。我通过 RegisterStartupScript 嵌入 Javascript,并通过 RegisterExpandoAttribute 将信息传递给验证。但是,用户控件在 PageLoad 上不可见,当我使用 document.getElementById 时,我得到空值。
这是我当前的代码:
public void Page_Load(object sender, EventArgs e)
{
ClientScriptManager cs = Page.ClientScript;
Type cstype = this.GetType();
if (!cs.IsStartupScriptRegistered(cstype, "ValidatorType"))
{
String DateValidator;
DateValidator = "<script type=\"text/javascript\">\n";
DateValidator += "function ValidateDate(source, args) {\n";
DateValidator += " var ddDay = document.getElementById(source.day);\n";
DateValidator += " var day = ddDay.selectedIndex;\n";
DateValidator += " var ddMonth = document.getElementById(source.month);\n";
DateValidator += " var month = ddMonth.selectedIndex;\n";
DateValidator += " var ddYear = document.getElementById(source.year);\n";
DateValidator += " var year = ddYear.selectedIndex;\n";
DateValidator += " if (day == 0 || month == 0 || year == 0)\n";
DateValidator += " args.IsValid = false;\n";
DateValidator += " else\n";
DateValidator += " args.IsValid = true;\n";
DateValidator += " }\n";
DateValidator += "</script>";
cs.RegisterStartupScript(cstype, "ValidatorType", DateValidator);
}
cs.RegisterExpandoAttribute(reqDueDate.ClientID, "month", ddMonth.ClientID);
cs.RegisterExpandoAttribute(reqDueDate.ClientID, "day", ddDay.ClientID, false);
cs.RegisterExpandoAttribute(reqDueDate.ClientID, "year", ddYear.ClientID, false);
}
我收到的错误是:
Uncaught TypeError: Cannot set property 'month' of null
Uncaught TypeError: Cannot read property 'selectedIndex' of null