asp.net Dropdownlist conditional postback

2019-07-18 17:46发布

I have a dropdownlist and have an event selectedIndexChanged which postsback, i want to be able to show a message to the user whenever he changes the value in dropdownlist, based on the input from the message i will decide if i have to postback or not.

The message shown would be are you sure? if he selects yes i would continue with postback, if he says no, i would cancel the postback and assign the previous value as selected.

I have searched alot but cant figure out a solution to this, i think if there is a javascipt function which determines if a postback is required or not that could help i guess

Thanks

3条回答
欢心
2楼-- · 2019-07-18 17:57

In order to accomplish this task you will need to use a CustomValidator with custom client side Javascript to control the post back.

You can read this article on 4Guys discussing the different validators with a client side validator JavaScript sample to get an idea.

But the core solution would be using a custom validator to control the post back only when the form is valid.

查看更多
ゆ 、 Hurt°
3楼-- · 2019-07-18 18:01
// 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, '');
  }
};
查看更多
Deceive 欺骗
4楼-- · 2019-07-18 18:14

You can stop can cancel postback of dropdownlist very simply.Just add this javascript on page load event.

protected void Page_Load(object sender, EventArgs e)
{
    DropDownList1.Attributes.Add("OnChange", "if (!confirm('Change this?')){return};");
}
查看更多
登录 后发表回答