Asp.net-Mvc

模型不適用 DataType.Password

  • August 28, 2013

我沒有直接使用該對象,而是在一個簡單的 Razor 視圖上使用了一個表單,它使用model了一個裝飾器對象。

public class GlobalAccount
{
   public GlobalAccount()
   {
       this.TestService = new TestServiceModel();
   }

   public TestServiceModel TestService { get; set; }
}

TestServiceModel表示為

public class TestServiceModel
{
   [Required]
   [Display(Name = "Endpoint (url of your service like http://mydomain/remote/)")]
   public string Endpoint { get; set; }

   [Required]
   [Display(Name = "System username")]
   public string UserName { get; set; }

   [Required]
   [DataType(DataType.Password)]
   [Display(Name = "System password")]
   public string Password { get; set; }
}

注意Password用_DataType.Password

在一個Partial Razor view我呼叫那個對象

@model OnlineServices.Administration.Models.GlobalAccount
...
@Html.TextBoxFor(model => model.TestService.Password, new { size = "30" })

問題是,在html我得到type="text"而不是text="password"

您可以在此圖像中看到整個流程:

在此處輸入圖像描述

我在這裡想念什麼?

您應該使用Html.Password,甚至更好地使用Html.EditorFor它將DataType.Password為您讀取並輸出密碼類型輸入。

Html.TextBoxFor只是基於文本的輸入,而不是基於密碼的輸入。

根據 Kieron 的回答,在 MVC3 中,實際上使用 Html.EditorFor 作為密碼輸入並不好,因為由於某種原因,如果伺服器返回頁面(比如使用者名密碼組合不正確),那麼使用 EditorFor,密碼會被傳輸返回頁面(並且查看原始碼可見)

使用 Html.PasswordFor 時,密碼不會傳回客戶端。

引用自:https://stackoverflow.com/questions/6044922