asp.net Dropdownlist conditional postback

孤人 提交于 2019-12-11 03:44:03

问题


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


回答1:


// 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, '');
  }
};



回答2:


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



回答3:


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.



来源:https://stackoverflow.com/questions/8697100/asp-net-dropdownlist-conditional-postback

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!