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

本文关键字:单个 属性 模型 绑定 验证 自定义 | 更新日期: 2023-09-27 18:06:57

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

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    
    }
}

在手动分配Score后,Mvc框架不会检查模型的有效性。现在我想验证得分属性与当前存在于模型上的所有验证属性。//如何做到这一点?Mvc框架支持这个场景吗?

这是我的模型

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

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

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

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

您正在使用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

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

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