问题
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