求助:如何在ASP.NET Web应用中禁用文本框自动完成功能
Hey there! I’ve battled this exact autocomplete problem in ASP.NET apps before, so I know how frustrating it is when standard blog solutions don’t work. Let’s go through the most reliable fixes that should get this sorted for you:
Direct Control Attributes (Web Forms & HTML)
For ASP.NET Web FormsTextBoxcontrols, combine the built-in property with the HTMLautocompleteattribute—some browsers ignore one or the other:<asp:TextBox ID="txtUserInput" runat="server" AutoCompleteType="Disabled" autocomplete="off"></asp:TextBox>If you’re using plain HTML inputs (or MVC), use either
autocomplete="off"orautocomplete="new-password"—the latter works better for modern browsers like Chrome that sometimes bypassoff:<input type="text" id="txtUserInput" name="txtUserInput" autocomplete="new-password" />Disable Autocomplete for Entire Forms
If you want to turn off autocomplete for all controls in a form, add the attribute directly to the<form>tag:<form id="mainForm" runat="server" autocomplete="off"> <!-- All your form controls here --> </form>JavaScript Workaround for Stubborn Browsers
Some browsers cache autocomplete data based on control names/IDs. Use JavaScript to dynamically override these values on page load:document.addEventListener('DOMContentLoaded', function() { // Target all text and password inputs const inputs = document.querySelectorAll('input[type="text"], input[type="password"]'); inputs.forEach(input => { input.setAttribute('autocomplete', 'off'); // Add a random suffix to the name to break browser caching input.setAttribute('name', `${input.name}_${Math.random().toString(36).slice(2, 10)}`); }); });ASP.NET MVC Helper Method
If you’re using MVC, pass the autocomplete attribute directly in yourTextBoxForhelper:@Html.TextBoxFor(m => m.UserInput, new { autocomplete = "off" })
A quick note: Modern browsers have gotten smarter about ignoring autocomplete="off" in certain scenarios (like login fields). If that’s your case, autocomplete="new-password" is often a better workaround, even for non-password fields—browsers won’t cache values marked with this.
内容的提问来源于stack exchange,提问作者Sourabh Tiwari

