Wednesday, March 16, 2011

ASP.NET MVC 3's Remote attribute for Model is plain cool! B-)

On your HomeController:

public JsonResult CheckIfUnique(string Username)
 return Users.Any(name => name.ToUpper() == Username.ToUpper()) ?
                // any non-true value is considered an invalid input
  Json(Username + " is already taken. Try another user name")

IList<string> Users
  return new string[]
    // common names
   "Michael", "John", "Jacob"

On your model:

[Remote("CheckIfUnique","Home", HttpMethod="post")] 
public string Username { get; set; }

That will call the CheckIfUnique method of HomeController automagically while you are entering an input. Gone are the days for you to manually code a javascript that invokes the controller/method and check if your input has a duplicate. It's all in the Model Luke! May the force(validations) be with you!

No comments:

Post a Comment