2010-08-02 36 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); 
}