Showing posts from August, 2012

ASP.Net MVC : Conditional Validation using ValidationAttribute

In ASP.Net MVC we can validate each input field by decorating the corresponding property in the model class with some validation attributes like Required , MaxLength , MinLength ,...etc. Sometime we need to validate a property according to another property value for example if we have a registration form and we need the user enter his age if he is a male and age not required if the user sex is female. So if we decorated the Age property with Required attribute it will show error message even if the user is female, so we need to bypass this check with females. Assume our registration form will contains three fields, name, sex and age, and its model will be as follows public class RegisterationModel { [Required(ErrorMessage = "*")] public String Name { get; set; } [Required(ErrorMessage = "*")] [Display(Name = "Gender")] public Sex Sex { get; set; } [RequiredIf("Sex", Sex.Male, "enter your age")] pu

Restrict non-ajax requests using ActionMethodSelectorAttribute

In ASP.Net MVC each coming request is routed to a certain action method inside some controller and with JQuery it became piece of cake to call this action method using ajax. In some scenarios we need to restrict the incoming requests to be ajax request only, fortunately ASP.Net MVC represent a new method to Request object called IsAjaxRequest() that return true if the current request come from ajax call and return false if current request is normal request(typing url in address bar of a browser, click a link to this page,..etc). We can use that method to deny any request come from ajax call or vise versa. public class HomeController { public ActionResult Index() { if(Request.IsAjaxRequest()) { //Do something } else { //Do something else } } } As we see if we need to make this check many times in our project, we will rewrite the same if statement for each action we need it be called via ajax only, but is there anot