我将一些值传递给我的控制器动作,一切都很好.POST设计中将缺少两个属性.
然后我设置缺失的值,但后来我想验证模型,它仍然是假的,因为看起来ModelState没有赶上我的更改.
[HttpPost, Authorize]
public ActionResult Thread(int id, string groupSlug, Comment comment, string submitButton)
{
comment.UserID = UserService.UID;
comment.IP = Request.UserHostAddress;
UpdateModel(comment); //throws invalidoperationexception
if (ModelState.IsValid) // returns false if i skip last line
{
//save and stuff
//redirect
}
//return view
}
Run Code Online (Sandbox Code Playgroud)
什么是最简洁的方法来轻拍模型状态并告诉它一切都会好的,同时仍然验证从用户的POST绑定的所有其他内容
KP.*_*KP. 39
如果模型需要缺少的值,但在绑定之后才会提供,则可能需要清除由这两个值引起的错误ModelState.
[HttpPost, Authorize]
public ActionResult Thread(int id, string groupSlug, Comment comment, string submitButton)
{
comment.UserID = UserService.UID;
comment.IP = Request.UserHostAddress;
//add these two lines
ModelState["comment.UserID"].Errors.Clear();
ModelState["comment.IP"].Errors.Clear();
UpdateModel(comment); //throws invalidoperationexception
if (ModelState.IsValid) // returns false if i skip last line
{
//save and stuff
//redirect
}
//return view
}
Run Code Online (Sandbox Code Playgroud)
我正在使用ASP.NET Core 1.0.0和异步绑定,对我来说解决方案是使用ModelState.Remove并传递属性名称(没有对象名称).
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Submit([Bind("AerodromeID,ObservationTimestamp,RawObservation")] WeatherObservation weatherObservation)
{
weatherObservation.SubmitterID = this.User.FindFirst(ClaimTypes.NameIdentifier)?.Value;
weatherObservation.RecordTimestamp = DateTime.Now;
ModelState.Remove("SubmitterID");
if (ModelState.IsValid)
{
_context.Add(weatherObservation);
await _context.SaveChangesAsync();
return RedirectToAction("Index", "Aerodrome");
}
return View(weatherObservation);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
12698 次 |
| 最近记录: |