2010-08-02 58 views
17

我传递了一些值给我的控制器动作,并且一切都很好地绑定。设计中POST的表单中缺少两个属性。更新我的模型,然后重新评估IsValid?

然后我设置缺少的值,但然后我想验证模型,它仍然说false,因为它看起来像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 
} 

什么是拍拍头上的ModelState中,并告诉它,一切都会好起来的,同时还确认其他一切从用户的POST

回答

33

势必如果需要的遗漏值最彻底的方法您的模型,但不会提供,直到绑定后,您可能需要清除由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 
} 
+0

这回答了这个问题。不过,我认为我的架构是错误的。我已经回去并改变了模型 – BritishDeveloper 2011-01-05 16:10:18

+0

似乎并不是ASP.NET Core 1.0.0中的解决方案 – 2016-08-23 23:29:24

4

我使用ASP.NET核心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); 
}