验证模型中的单个属性,该属性是自定义绑定的

时间:2011-08-26 15:08:26

标签: c# .net asp.net-mvc asp.net-mvc-3

我想简单地验证该模型的单个属性

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 Framework支持这种情况吗?

这是我的模特

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

3 个答案:

答案 0 :(得分:1)

我找到了正确的解决方案。我只是调用TryValidateModel,它验证属性包括Score属性。

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

}

答案 1 :(得分: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

答案 2 :(得分:0)

您需要在Controller Action中检查ModelState是否有效:

public ActionResult Action(RatingModel viewModel)
{
    if (ModelState.IsValid) 
    {
        //Model is validated
    }
    else
    {
        return View(viewModel);
    }
}
相关问题