Thursday, 23 May 2013

Remote attribute in MVC

Hello,

Many time we get situation where we want to check for validation on client side rather than going to server side and show list of errors.E.g. check for email exists or not.It would be great if we could show email exists or not on every letter typed in textbox.We can achieve that in mvc with help of [Remote] attribute.

Here I am going to show it for this example.

Step 1) Put remote attribute on property that you want to check.

[Remote("IsEmailExists", "Promoter", AdditionalFields = "ID,CreateId", ErrorMessage = "Email Address already exists")]
public String Email { get; set; }

Here "Promoter" is my controller name and "IsEmailExists" is action method in  "Promoter"controller.

Additional fields are those properties that you want to pass to method.Hense it is compulsory that we have ID and CreateId properties in model.

 public int ID{ get; set; }
 public Nullable<Guid> CreateId { get; set; }


Step 2) Create "IsEmailExists" action method in "Promoter" controller.

 public ActionResult IsEmailExists(string Email, int? ID, Guid? CreateId)
        {
            if (_IPromoterProcessor.IsEmailExists(Email, ID, CreateId))
            {
                return Json(false, JsonRequestBehavior.AllowGet);//Show error message
            }
            return Json(true, JsonRequestBehavior.AllowGet);
        }

IsEmailExists() is my method which will contain linq query that will check if email exists or not.Query is as follow.

public bool IsEmailExists(string Email, int? ID, Guid? CreateId)
        {
            return DbSet.Any(x => x.Email.Equals(Email) && (CreateId == null || x.CreateId == CreateId) && (ID == null || x.ID != ID));
        }

NOTE:

If you have same view page for add and edit page, in that case at the time of record insertion, you will have ID and CreateId null.

Step 3) Show message in view

        @Html.LabelFor(model => model.Email)
        @Html.TextBoxFor(model => model.Email)
        @Html.ValidationMessageFor(model => model.Email)

Summary:

When you type character in email textbox,it will call IsEmailExists().If email exists then it will show message instantly.


No comments:

Post a Comment