Niveditha Niveditha - 1 year ago 66
ASP.NET (C#) Question

Validation Message in MVC for extracting the unique values by validating from database

I am new to MVC. I want to add a Validation Message for a input textbox in a cshtml file. The input should have the building names. It should only take the unique names after validating from the database. How should I write the validation message for this input box. Please help.
The code is below:

<td style="height: 0.3em;width: 22em;">
<div style="margin-top: -0.0em;margin-left: 0.8em;">
@Html.TextBoxFor(model => model.buildingName, new { @class = "InfoTextBox", @placeholder = "Building name", id = "buildingName", maxlength = 25, onkeyup = "FormDirty();" })
<br />
@Html.ValidationMessageFor(model => model.buildingName)
<span style="position: absolute; top: 6.6em; left: 14.8em; color: #FF0000; font-size: 1.7em;">*</span>

I have to enhance the validation by only letting it take the unique values. Please help

Answer Source

You can use DataAnotation Remote attribute for this like below:

ViewModel :

    [System.Web.Mvc.Remote("CheckBuildingName", "ControllerName", AdditionalFields = "buildingName", HttpMethod = "Post")]
    public string buildingName { get; set; }


public JsonResult CheckBuildingName() {
    string _buildingName = Request.Form["buildingName"]; // put your control name here
    if (repository.isExist(_buildingName)) {
        return Json("Building already taken, Pleaes try with different name.", JsonRequestBehavior.AllowGet);
    } else {
        return Json(true, JsonRequestBehavior.AllowGet);

Your .cshtml code seems fine.

Hope this will helps you.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download