Validating single Property in model which is binded customly
I want to simply validate a single property of that model
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
}
}
after assign Score manually, Mvc framework does not che开发者_开发技巧ck validation on model. Now i want to validate Score property with all validation attributes which currently exist on model. // How to do that easily ? Mvc Framework support this scenario ?
Here is my model
public class RatingModel
{
[Range(0,5),Required]
public int Score { get; set; }
}
I have found right solution. I simply call TryValidateModel and it validate properties include Score property.
public ActionResult Rate([Bind(Exclude="Score")]RatingModel model)
{
model.Score = ParseScore( Request.Form("score"));
if(TryValidateModel(model))
{
///validated with all validations
}
}
You're using MVC3. Any particular reason why you aren't setting some of the most basic validation rules in the Model?
You can set some validation rules directly in the model. For example, if you want to validate an email field, you can set the rules and even the error messages in the model itself.
[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; }
Read more here: http://www.asp.net/mvc/tutorials/validation-with-the-data-annotation-validators-cs
You need to check if the ModelState is valid in the Controller Action:
public ActionResult Action(RatingModel viewModel)
{
if (ModelState.IsValid)
{
//Model is validated
}
else
{
return View(viewModel);
}
}
精彩评论