asp.net下拉列表条件回发

asp.net Dropdownlist conditional postback

本文关键字:条件 下拉列表 net asp      更新时间:2023-09-26

我有一个下拉列表,并有一个事件selectedIndexChanged其中postsback,我希望能够显示一个消息给用户,每当他改变下拉列表中的值,根据从消息的输入,我将决定我是否要回发。

显示的信息是are you sure?如果他选择"是",我将继续回发,如果他选择"否",我将取消回发,并将前一个值指定为所选值。

我已经搜索了很多,但无法找出解决方案,我想如果有一个javascript函数确定是否需要回发,可以帮助我猜

谢谢

// get a reference to the DropDownList
var selectlistId = '<%= ddlYourList.ClientID %>',
    selectlist = document.getElementById(selectlistId);
// attach to the onchange event
selectlist.onchange = function() {
  // decide whether to execute the __doPostBack event, which submits the
  // form back to the server
  if(confirm("Are you sure you want to do this?")){
     __doPostBack(selectlistId, '');
  }
};

您可以很简单地停止或取消下拉列表的回发。只需在页面加载事件中添加这个javascript。

protected void Page_Load(object sender, EventArgs e)
{
    DropDownList1.Attributes.Add("OnChange", "if (!confirm('Change this?')){return};");
}

为了完成这个任务,您需要使用CustomValidator和自定义客户端Javascript来控制回发。

您可以阅读4Guys上的这篇文章,通过一个客户端验证器JavaScript示例来讨论不同的验证器。

但是核心的解决方案是使用自定义验证器来控制只有当表单有效时才返回。