我有以下MVC视图和控制器。当我提交表格时。它传入Id而不是ChangeUserViewModel。
查看:
@model AppTransactionsManagement.Models.ChangeUserViewModel
<div>
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title" id="myModalLabel">Change Password</h4>
</div>
@using (Html.BeginForm("ChangePassword", "UsersAdmin", FormMethod.Post))
{
@Html.AntiForgeryToken()
<div class="modal-body">
<div class="form-horizontal">
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
@Html.HiddenFor(model => model.Id)
<div class="form-group">
@Html.LabelFor(model => model.Email, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.TextBoxFor(model => model.Email, new { @class = "form-control" })
@Html.ValidationMessageFor(model => model.Email, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Password, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Password, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Password, "", new { @class = "text-danger" })
</div>
</div>
</div>
</div>
<div class="modal-footer">
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<button class="btn" data-dismiss="modal" aria-hidden="true">Close</button>
<input type="submit" value="Save" class="btn btn-primary" />
</div>
</div>
</div>
}
</div>
控制器:
[HttpPost]
[ValidateAntiForgeryToken]
private async Task<ActionResult> ChangePassword(ChangeUserViewModel model)
{
if (ModelState.IsValid)
{
//Get the user manager and user. (if the user is not found, user will be null)
ApplicationUser user = await UserManager.FindByIdAsync(model.Id);
if (user == null)
{
return PartialView("_ChangePassword");
}
else
{
user.PasswordHash = UserManager.PasswordHasher.HashPassword(model.Password);
UserManager.UpdateSecurityStamp(user.Id.ToString());
//Save Changes
IdentityResult result = await UserManager.UpdateAsync(user);
if (result.Succeeded)
{
return Json(new { success = true });
}
else
{
var error = result.Errors.FirstOrDefault();
return PartialView("_ChangePassword");
}
}
}
return PartialView("_ChangePassword");
}
型号:
public class ChangeUserViewModel
{
public string Id { get; set; }
[Required(AllowEmptyStrings = false)]
[Display(Name = "Email")]
[EmailAddress]
public string Email { get; set; }
[Required]
[StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
[DataType(DataType.Password)]
[Display(Name = "Password")]
public string Password { get; set; }
}
我做错了什么?
答案 0 :(得分:3)
您已将方法标记为private
,这将使其无法访问。您不能POST
使用私有方法。这很可能是你的问题。将其更改为
[HttpPost]
public async Task<ActionResult> ChangePassword(ChangeUserViewModel model)
{
......
......
}
答案 1 :(得分:1)
尝试在控制器操作中使用模型绑定。
public async Task<ActionResult> ChangePassword([Bind(Include = "Id, Email, Password")]ChangeUserViewModel model) {}