ASP.NET - MVC - HtmlHelper - Password

HtmlHelper - Password

Lớp HtmlHelper có hai phương thức mở rộng để tạo (<input type="password'>) trong Razor là : Password() và PasswordFor(). Phương thức Html.Password() tạo phần tử <input type="Password" /> với tên được chỉ định, giá trị và thuộc tính html.Html. PasswordFor tạo ra một phần tử <input type="Password" /> với thuộc tính model xác định sử dụng một biểu thức lambda.

Ví dụ Password() và PasswordFor():

public class Student
{
    public int StudentId { get; set; }
    [Display(Name="Name")]
    public string StudentName { get; set; }
    public int Age { get; set; }
    public bool isNewlyEnrolled { get; set; }
    public string OnlinePassword { get; set; }
}

Password()

Phương thức Html.Password() tạo ra một phần password với các thuộc tính tên, giá trị và html.

Cú pháp phương thức Password():

MvcHtmlString Html.Password(string name, object value, object htmlAttributes)

Password có nhiều phương thức. Vui lòng truy cập MSDN để biết tất cả Password.

Ví dụ Html.Password():

@model Student

@Html.Password("OnlinePassword")

Kết quả HTML:

<input 
        id="OnlinePassword" 
        name="OnlinePassword" 
        type="password" 
        value="" />

Ví dụ trên sẽ tạo trường mật khẩu cho thuộc tính "OnlinePassword" như bên dưới.

Output in the browser


PasswordFor()

PasswordFor tạo ra một phần tử <input type="password"> với thuộc tính xác định sử dụng một biểu thức lambda.

Cú pháp phương thức PasswordFor

MvcHtmlString Html.PasswordFor(Expression<Func<dynamic,TProperty>> expression, object htmlAttributes)

Xem thêm các phương thức của PasswordFor.

Ví dụ: PasswordFor ()

@model Student

@Html.PasswordFor(m => m.Password)

Kết quả HTML:

<input id="Password" name="Password" type="password" value="mypassword" />

Trong ví dụ trên, tham số đầu tiên trong phương thức PasswordFor () là biểu thức lambda chỉ định thuộc tính trong Model được liên kết với hộp văn bản mật khẩu. Chúng ta  đã chỉ định thuộc tính Mật khẩu trong ví dụ trên. Vì vậy, nó tạo ra phần tử password đầu vào với id & name được đặt thành tên thuộc tính. Thuộc tính value sẽ được đặt thành giá trị của thuộc tính Mật khẩu là "mypassword" trong ví dụ trên.