Client side validation for unique field mvc

asp.net-mvc-4 entity-framework unobtrusive-validation

Question

I need to implement unique validation check for my field

[Key]
[Required]
[DisplayName("Tag")]
public string Tag { get; set; }  

Error this Tag Already Exist...

1
2
8/4/2013 6:23:35 PM

Accepted Answer

You can use the remote validate rule for this purpose. Add this rule [Remote("IsTagAvailble", "MyController", ErrorMessage = "Tag Already Exist.")] to your Tag field. You new code will be

[Key]
[Required]
[DisplayName("Tag")]
[Remote("IsTagAvailble", "MyController", ErrorMessage = "Tag Already Exist.")]
public string Tag { get; set; }

The first parameter is the Action name and second parameter is your controller name and third parameter is the error text to display to the user. Now Define this new action in your controller e.g MyController in sample.

public class MyController : Controller
{
    public ActionResult IsTagAvailble(string Tag)
    {
        using (DataBaseContext db = new DataBaseContext())
        {
            try
            {
                var tag = db.TABLE_NAME.Single(m => m.Tag == Tag);
                return Json(false, JsonRequestBehavior.AllowGet);
            }
            catch (Exception)
            {
                return Json(true, JsonRequestBehavior.AllowGet);
            }
        }
    }
}

This will remotely validate the uniqueness of the Tag filed and display error to the user using unobtrusive javascript.

Finally your view should be something like

@Html.TextBoxFor(m => m.Tag) @Html.ValidationMessageFor(m => m.Tag)
14
8/4/2013 1:46:47 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow