2011-08-26 66 views
0

我想分配分數後,只需驗證模型驗證模型單一屬性被綁定customly

public ActionResult Rate([Bind(Exclude="Score")]RatingModel model) 
{  
    if(ModelState.IsValid) 
    { 
     //here model is validated without check Score property validations 
     model.Score = ParseScore(Request.Form("score")); 
     // Now i have updated Score property manualy and now i want to validate Score property  
    } 
} 

的單一屬性手動,MVC框架不會對模型檢查驗證。現在我想用模型上當前存在的所有驗證屬性來驗證Score屬性。 //如何輕鬆做到這一點? Mvc框架支持這種情況?

這裏是我的模型

public class RatingModel 
{ 
    [Range(0,5),Required] 
    public int Score { get; set; } 
}  

回答

1

我已經找到了合適的解決方案。我只是調用TryValidateModel,它驗證屬性包括Score屬性。

public ActionResult Rate([Bind(Exclude="Score")]RatingModel model) 
{  
    model.Score = ParseScore(Request.Form("score")); 
    if(TryValidateModel(model)) 
    { 
     ///validated with all validations 
    } 

} 
0

您正在使用MVC3。您爲什麼不在模型中設置一些最基本的驗證規則的任何特定原因?

您可以直接在模型中設置一些驗證規則。例如,如果要驗證電子郵件字段,則可以在模型中設置規則甚至錯誤消息。

[Required(ErrorMessage = "You must type in something in the field.")] 
[RegularExpression(".+\\@.+\\..+", ErrorMessage = "You must type in a valid email address.")] 
[Display(Name = "Email:")] 
public string Email { get; set; } 

在這裏閱讀更多: http://www.asp.net/mvc/tutorials/validation-with-the-data-annotation-validators-cs

+0

嘿,你錯過了我。我知道你說了什麼。請檢查問題的更新版本。如果我有一個理由手動綁定Score屬性如何獲得ModelState.Valid檢查的好處?我希望能夠以簡單的方式完成此操作,而無需讀取屬性並將錯誤添加到ModelState.AddModelError方法中 – Freshblood

0

你需要檢查的ModelState是在控制器動作有效:

public ActionResult Action(RatingModel viewModel) 
{ 
    if (ModelState.IsValid) 
    { 
     //Model is validated 
    } 
    else 
    { 
     return View(viewModel); 
    } 
} 
+0

@Marting - 爲了使其更清晰,我重新提出了我的問題。你可以檢查reagain? – Freshblood

+0

你在模型綁定時不包括分數......爲什麼你不包括它,它會爲你驗證? – Martin

+0

MVC無法綁定該屬性,這就是爲什麼我要綁定它的自定義方式。如果我包含它,那麼ModelState.IsValid將始終爲false。這就是爲什麼它被排除在外。 – Freshblood