2017-02-24 48 views
-1

我正在嘗試啓用顯示/隱藏密碼功能。我正在使用C#創建一個asp.net web表單。嘗試在asp.net中啓用顯示/隱藏功能

我的代碼如下,

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Web; 
using System.Web.UI; 
using System.Web.UI.WebControls; 

public partial class show : System.Web.UI.Page 
{ 
    protected void Page_Load(object sender, EventArgs e) 
    { 

    } 

    protected void CheckBox1_CheckedChanged(object sender, EventArgs e) 
    { 
     if (CheckBox1.Checked == false) 
     { 
      TextBox1.TextMode = TextBoxMode.Password; 
     } 

     if (CheckBox1.Checked == true) 
     { 
      TextBox1.TextMode = TextBoxMode.SingleLine; 
     } 
    } 
} 

在mypage.aspx,

有一個複選框,其AutoPostBack屬性爲true,並且其文本框文本模式是密碼。

預期的結果是: -

顯示密碼輸入文本時複選框被選中。

未選中複選框時隱藏密碼。

的問題是: -

此代碼工作只有一次,即當複選框被選中或取消選中它再次沒有被執行。 該文本框變爲空白。

請儘快幫助我。

+1

我建議不使用後這樣做了。當它主要應該是客戶端JavaScript時,這是一個非常繁重的方式。 –

+0

感謝Kay Lee審查我的帖子。 –

回答

0

您在TextBox內丟失了值,因爲在選擇更改後,頁面再次加載,您需要檢查其是否爲postBack或第一次加載並設置textBox值。

protected void Page_Load(object sender, EventArgs e) 
    { 
     if (IsPostBack) 
     { 
      string Password = TextBox1.Text; 
      TextBox1.Attributes.Add("value", Password); 
     } 
    } 

您的問題將得到解決。我測試過了。

希望它有幫助!

+0

謝謝。它對我有幫助。 –

0

後更改模式

if (CheckBox1.Checked == false) 
      { 
       string pass = TextBox1.Text; 
       TextBox1.TextMode = TextBoxMode.Password; 
       TextBox1.Attributes.Add("value", pass); 

      } 

      if (CheckBox1.Checked) 
      { 
       TextBox1.TextMode = TextBoxMode.SingleLine; 
      } 
1

有完全的零需要使用回傳這個你不能設置安全密碼類型字段的text屬性reasons.So另一種方式來設置的值。 An example using jQuery

標記:

<label>Password fields are just a UI convenience:</label> 
<input type="password" id="password" value="super secret password" /> 
<label> 
    <input type="checkbox" id="toggle-password" /> Toggle 
</label> 

jQuery代碼:

$(function() { 
    $('#toggle-password').on('change', function(e) { 
    var _this = $(this); 

    if (_this.is(':checked')) { 
     $('#password').attr({ 
     'type': 'text' 
     }); 
    } else { 
     $('#password').attr({ 
     'type': 'password' 
     }); 
    } 
    }) 
}); 

A vanilla JS version

var toggle = document.getElementById('toggle-password'); 
var textbox = document.getElementById('password'); 

toggle.addEventListener("click", function() { 
    var isChecked = toggle.checked; 

    if (isChecked) { 
    textbox.type = "text"; 
    } else { 
    textbox.type = "password"; 
    } 
})