在控制器的行動,我有以下的呼叫,其中userId
是一種已知的非空值:ASP.NET MVC模型屬性爲空時,POST方法被調用
return View("ChangePassword", new ChangePasswordBindingModel(userId));
這裏是ChangePasswordBindingModel的定義:
public class ChangePasswordBindingModel
{
private string currentUserId;
[Required]
[DataType(DataType.Password)]
//[Display(Name = "Current password")]
public string OldPassword { get; set; }
[Required]
//[StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
[DataType(DataType.Password)]
[Display(Name = "New password")]
public string NewPassword { get; set; }
[Required]
[DataType(DataType.Password)]
//[Display(Name = "Confirm new password")]
[Compare("NewPassword", ErrorMessage = "The new password and confirmation password do not match.")]
public string ConfirmPassword { get; set; }
public ChangePasswordBindingModel()
{
}
public ChangePasswordBindingModel(string userId)
{
this.currentUserId = userId;
}
public string GetUserId()
{
return this.currentUserId;
}
}
這裏是綁定到該模型ChangePassword視圖:
@model IdentityDevelopment.Models.ChangePasswordBindingModel
@{ ViewBag.Title = "ChangePassword";
}
@Html.ValidationSummary(false)
<h2>Change Password</h2>
@using (Html.BeginForm("ChangePassword","Account", FormMethod.Post))
{
@Html.AntiForgeryToken();
<input type="hidden" name="returnUrl" value="@ViewBag.returnUrl" />
<div class="form-group">
<label>Current Password</label>
@Html.PasswordFor(x => x.OldPassword, new { @class = "form-control" })
</div>
<div class="form-group">
<label>New Password</label>
@Html.PasswordFor(x => x.NewPassword, new { @class = "form-control" })
</div>
<div class="form-group">
<label>Re-enter New Password</label>
@Html.PasswordFor(x => x.ConfirmPassword, new { @class = "form-control" })
</div>
<!-- <button class="btn btn-primary" type="submit">Save</button> -->
<input class="btn btn-primary" type="submit" value="Save" />
}
最後,這裏是點擊Save
上述形式的Post方法:
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> ChangePassword(ChangePasswordBindingModel loginChange)
{
if (ModelState.IsValid)
{
IdentityResult result = null;
try
{
string userid = loginChange.GetUserId();
result = await UserManager.ChangePasswordAsync(userid, loginChange.OldPassword, loginChange.NewPassword);
}
catch (Exception ex)
{
}
if (result != null && result.Succeeded)
{
return RedirectToAction("Index");
}
else
{
if(result != null)
{
AddErrorsFromResult(result);
}
}
}
return View(loginChange);
}
的問題是,userid
不會被設置爲一個非空值,因爲我認爲GetUserId()
會做。爲什麼發送到post方法的模型的currentUserId
屬性不包含該值?我確認在調試過程中通過調用GetUserId()
來確認。
我想你需要使該字段currentUserId公衆它是JSON序列化,還包括它在剃刀標記,以便獲取是從客戶端 –
發送回服務器@ Sam.C是的,謝謝,這是基於有效答案的高層次觀點。 – ITWorker