我在页面上有自定义验证器:
<asp:CustomValidator ID="CustomValidator2" runat="server"
ControlToValidate="ddlProposer" ErrorMessage="Please select some values."
Display="Dynamic" onservervalidate="CustomValidator2_ServerValidate"
ClientValidationFunction="CustomValidator2_ClientValidate">
</asp:CustomValidator>
当服务器端列表不为空(或ListCount
变量&gt; 0)时,它必须有效。加载页面后,此列表可能会更改(通过更新面板上的按钮):
public partial class Pages_Application_Application : System.Web.UI.Page
{
protected List<IdValue> ProposersList
{
get
{
if (ViewState["proposersList"] == null)
ViewState["proposersList"] = new List<IdValue>();
return ViewState["proposersList"] as List<IdValue>;
}
set
{
ViewState["proposersList"] = value;
}
}
public int ListCount
{
get
{
return this.ProposersList.Count;
}
}
...
服务器端验证没有问题:
protected void CustomValidator2_ServerValidate(object source, ServerValidateEventArgs args)
{
args.IsValid = this.ProposersList.Count > 0;
}
问题在于客户端部分。我一直在尝试这样的事情:
<script type="text/javascript">
function CustomValidator2_ClientValidate(source, arguments) {
var serverVariable = <%= ListCount %>;
alert(serverVariable);
arguments.IsValid = serverVariable > 0;
}
</script>
但是,它仅在第一页加载时触发,而ListCount变量始终为0(serverVariable也是如此)。
问题是:是否有一种简单方法可以使其正常工作?那么Javascript获取某个服务器端变量的当前值?
答案 0 :(得分:1)
你必须在普通的javascript中完成它,并且没有获得服务器端变量的感觉,因为它将在客户端验证完成时不会是最新的。
你需要的是将你的ddl html元素传递给你的CustomValidator2_ClientValidate
函数并检查它是否包含option
html元素,这应该可以解决问题。
答案 1 :(得分:1)
您可以在页面级别使用隐藏变量,也可以从服务器端设置其值并在客户端进行验证。
<input type="hidden" id="ListCount" runat="server" value="0" />
public partial class Pages_Application_Application : System.Web.UI.Page
{
protected List<IdValue> ProposersList
{
get
{
if (ViewState["proposersList"] == null)
ViewState["proposersList"] = new List<IdValue>();
return ViewState["proposersList"] as List<IdValue>;
}
set
{
ViewState["proposersList"] = value;
ListCount=value;
}
}
public int ListCount
{
get
{
return this.ProposersList.Count;
}
}
<script type="text/javascript">
function CustomValidator2_ClientValidate(source, arguments) {
var count= document.getElementById("ListCount").value;
alert(count);
arguments.IsValid = count > 0;
}