我想简单地验证该模型的一个属性
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; }
}
发布于 2011-08-26 21:13:14
我找到了正确的解决方案。我只需调用TryValidateModel,它就会验证包括Score属性在内的属性。
public ActionResult Rate([Bind(Exclude="Score")]RatingModel model)
{
model.Score = ParseScore( Request.Form("score"));
if(TryValidateModel(model))
{
///validated with all validations
}
}
发布于 2011-08-26 15:21:56
您正在使用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
发布于 2011-08-26 18:23:57
您需要在控制器操作中检查ModelState是否有效:
public ActionResult Action(RatingModel viewModel)
{
if (ModelState.IsValid)
{
//Model is validated
}
else
{
return View(viewModel);
}
}
https://stackoverflow.com/questions/7206786
复制相似问题