我在一个网页表单中有6个复选框:
<input type="checkbox" name="mammals" id="mammals" runat="server" checked"/> Mammals <br />
<input type="checkbox" name="birds" id="birds" runat="server" /> Birds <br />
<input type="checkbox" name="reptiles" id="reptiles" runat="server" /> Reptiles <br />
id="amphibians" runat="server" /> Amphibians <br />
<input type="checkbox" name="fishes" id="fishes" runat="server" /> Fishes <br />
<input type="checkbox" name="invertebrates" id="invertebrates" runat="server" /> Invertebrates
如果存在某些条件,我将它们设置为Checked = true
-这段代码在页面加载时执行:
if (isMammals)
mammals.Checked = true;
if (isBirds)
birds.Checked = true;
if (isReptiles)
reptiles.Checked = true;
if (isAmphibians)
amphibians.Checked = true;
if (isFishes)
fishes.Checked = true;
if (isInvertebrates)
invertebrates.Checked = true;
但即使用户取消选中复选框并单击提交(输入类型提交)Checked
仍然是true
-单击提交后执行此代码:
isMammals = mammals.Checked;
isBirds = birds.Checked;
isReptiles = reptiles.Checked;
isAmphibians = amphibians.Checked;
isFishes = fishes.Checked;
isInvertebrates = invertebrates.Checked;
这个变量的值仍然是true
。我如何修复它?谢谢
1条答案
按热度按时间gk7wooem1#
Remember, on ANY button click, or ANYTHING that causes a page post back?
Your on-load event fires EACH time, and runs BEFORE any other controls event stub.
So, be is a simple button and a click, or a dropdown list (say with autopost-back = true)?
The page load event will run first, and run EACH time, and BEFORE your event stub you have for the button or control in question.
As a result, the last 200 web pages I have created?
Every SINGLE one of those pages has this code stub:
So, in your case, your page load event needs to be:
so, the event order is:
You can check further information about the Page events in the ASP.NET Page Life Cycle Overview
So, after the page load code runs, then you have this code + your button code.
So, above code, when it runs will run AFTER the page load code that sets the check boxes. If you leave out the !IsPostBack, then the page load event will change and OVERWRITE any changes the user makes.
As a result, you really can't even make a practial working web page UNLESS you include + use + adopt + take into account the required
!IsPostBack
stub that you need in 99% of cases.So, in page load event, you are 100% free to load up a gridview, load up some dropdown lists, setiup some checkboxes (as your example has), but since this code runs on EVERY page-post back?
Then you need that code stub inside of the
!IsPostBack
stub, and without that code wrapped inside of the !IsPostBack code block, then you are overwriting the users choice each and EVERY time the page loads.