在ASP.NET MVC中将文本框类型转换为密码

29

我该如何在asp.net mvc中将文本框类型转换为密码类型?

11个回答

70
只需在Razor视图中编写,即在.cshtml文件的下面一行。
  @Html.PasswordFor(m=>m.Password)

这里m是模型对象,password是密码字段名称。


22
你的意思是指 <%=Html.Password("test")%> 这段代码吗?

2
我希望我的文本框在密码输入时显示 *** 而不是明文。 - Fraz Sundal
1
所以,是的,你应该使用上面的代码。或者,<input type="password" name="mypass">。 - Palantir
我猜这个人在使用 ASP.NET MVC 中的 Razer 视图。 - Rusty
1
请注意,自MVC 1以来,这不是有效的语法,我们现在使用的是MVC 5(+),您应该使用Razor语法 - Liam

14

可以使用HTML辅助函数Password

<%= Html.Password("Password") %>

或者在输入字段上使用type参数:

<input name="password" type="password" />

请查看此页面上的第4和第5个代码清单。


5

在ASP.NET MVC中,有许多使用密码文本框的类型。

使用html控件时,可以像这样实现:

<input type="password" name="xx" id="yy">

使用 Razor 语法,它会像这样;
@Html.Password(name, value, html_attributes)

在强类型视图中,您可以编写以下代码:

或在强类型视图中,您可以编写

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

3
当使用强类型视图和Bootstrap时,请使用以下代码确保密码字段的样式正确: ```html @Html.PasswordFor(m => m.Password, new { @class = "form-control" }) ```
@Html.PasswordFor(model => model.Password, new { @class = "form-control" })

2
以下是基于HTML助手的扩展:
转换之前:
@Html.TextBox("mypass", null, new { style = "width: 200px;" })

转换后:

@Html.Password("mypass", null, new { style = "width:200px;" })

希望能对某人有所帮助。


1
在.cshtml文件中:
@Html.PasswordFor(modal => modal.Password)

1
为什么不加一些解释呢?在回答中添加解释总是一个好习惯,因为它有助于提问者和其他人理解你所尝试的内容。 - Gerhard
1
这只是重申别人已经说过多次的内容,请不要这样做。 - Liam

1
另一种方法是将@type = password添加到您的html.texbox()属性中,如下所示:

转换之前:

@Html.TextBox("mypass", null, new { @class = "" })

转换后:

@Html.TextBox("mypass", null, new { @class = "", @type = password })

这将使用圆圈而不是文本来遮盖您的文本框文本。它这样做,因为@type = password属性告诉您的文本框它是"密码"类型。
将文本框转换为密码类型的方法是从标准剃刀表单文本框中进行快速简便的转换。

我在这里找到了最好的答案。这不会破坏设计。谢谢。 - Harshith C

1
    <div class="editor-field">
        @Html.PasswordFor(model => model.Password, new { htmlAttributes = new { @class = "form-control", placeholder = "Password" } })
        @Html.ValidationMessageFor(model => model.Password)
    </div>

0
 @Html.EditorFor(model => model.Password, 
      "Password",
       new { htmlAttributes = new { @class = "form-control" } })

2
你的代码行缺乏上下文和解释,请添加一些说明。 - Ishita Sinha

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接