Last active
December 17, 2015 07:18
-
-
Save keithbloom/5571384 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class FoodViewModel | |
{ | |
public string FavouriteFood { get; set; } | |
} | |
public ActionResult UpdateFood(FoodViewModel viewModel) | |
{ | |
if(ModelState.IsValid) | |
{ | |
UpdateStats(viewModel.FavouriteFood); | |
return RedirectToAction("Thanks"); | |
} | |
return View(viewModel); | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public ActionResult UpdateFood(FoodViewModel viewModel) | |
{ | |
if(viewModel.FavouriteFood.Contains("House")) | |
{ | |
ModelState.AddModelError("","House is not a food"); | |
} | |
if (!ModelState.IsValid) | |
{ | |
return View(viewModel); | |
} | |
UpdateStats(viewModel.FavouriteFood); | |
return RedirectToAction("Thanks"); | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public interface IValidatableObject | |
{ | |
IEnumerable<ValidationResult> Validate(ValidationContext validationContext) | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class FoodViewModel : IValidatableObject | |
{ | |
public string FavouriteFood { get; set; } | |
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext) | |
{ | |
if (FavouriteFood.Contains("House")) | |
{ | |
yield return new ValidationResult("Sorry, house is not a food"); | |
} | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var validationResults = new List<ValidationResult>(); | |
var viewModel = Activator.CreateInstance(typeof (FoodViewModel)) as IValidatableObject; | |
if (viewModel != null) | |
{ | |
validationResults.AddRange(viewModel.Validate(null)); | |
} | |
foreach (var validationResult in validationResults) | |
{ | |
Console.WriteLine(validationResult.ErrorMessage); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment