ASP.Net MVC3 Html.PasswordFor does not populate
In my view I have the following element
@Html.PasswordFor(model => model.Password)
This is on a screen that creates/updates user details. When I am trying to update the user this field remains blank. When I change this element to a TextBoxFor it gets the data. How 开发者_运维问答do I get to populate the Password field.
As described above, it is better to avoid doing this for security reason. if you still want to persist the password so that you proceed from where the current validation failed, you can use the HTML helper with html attribute parameter:
Html.PasswordFor(x => x.Password, new { value = Model.Password})
This is as designed. Passwords are not filled to prevent accidental resubmits, and to prevent the page from containing unencrypted passwords. Obviously the password was wrong to begin with if you're posting back the credentials.
In your case, you could create an extension that does input the data, or just use an HTML input of type password.
MVC protects you from doing something like this for a reason. You shouldn't actually be able to do this because the users password should not be stored unencrypted and unhashed. If your goal is to end end up on http://plaintextoffenders.com/ though, you can do something like:
<input type="password" name="Password" id="Password" value="@Model.Password" />
I found this workaound. I needed my password shown in the form:
@model User
@{
@Html.Label(Model.Username, new { @class = "label" })
@Html.TextBoxFor(Model => Model.Username, new { @class = "form-control" })
@Html.Label(Model.Password, new { @class = "label" })
@Html.TextBoxFor(Model => Model.Password, new { @class = "form-control make-pass" })
}
<script type="text/javascript">
$(".make-pass").attr("type", "password");
</script>
This will make your input password-type without losing the value.
As mentioned before, its by design. But that can be wrong. We just got a new user who was confused by the empty password after the page refresh when he just added a password. So a simple fix is to change the label 'Password' to 'New password'. Now its clear why this input box is always empty.
If you're using asp-for attribute you can also do:
<input type="password" placeholder="@(Model.Password != null ? String.Concat(Model.Password.ToCharArray().Select(p=>"*")) : "Password")" asp-for="Password">
精彩评论