Niveditha Niveditha - 2 months ago 10
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:

<tr>
<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>
</div>
</td>


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

Answer

You can use DataAnotation Remote attribute for this like below:

ViewModel :

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

Controller:

[AcceptVerbs(HttpVerbs.Post)]
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.