Error based on Remote Validation in mvc

2019-07-19 03:44发布

This is my controller code:

   [AcceptVerbs(HttpVerbs.Post)]
    public JsonResult CheckBuildingName()
    {
        var isUnique = true;
        string _buildingName = Request.Form["buildingName"]; // put your control name here
        var connectionstring = ConnectionProvider();
        AddBuildingModel model = new AddBuildingModel();
        using (var context = new Notifier.AccountDatabase(connectionstring))
        {
            var objBuilding = (from building in context.Buildings
                               where building.buildingName == model.buildingName && building.buildingActive == true
                               select building).FirstOrDefault();

            if (objBuilding == null)
            {
                isUnique = true;


            }
            else
            {
                isUnique = false;
            }
        }
        if (isUnique == false)
        {
            return Json("Building already taken, Pleaes try with different name.", JsonRequestBehavior.AllowGet);
        }
        else
        {
            return Json(true, JsonRequestBehavior.AllowGet);
        }
    }
}

and my model is like below:

[System.ComponentModel.DisplayName("buildingName")]
[Remote("CheckBuildingName", "ConfigLocationController",ErrorMessage = "Building already exists!")]
public string buildingName { get; set; }

I am getting errors on this. The controller path cannot be found out or does not implement IController. What does that mean. Am I missing something ? Or is my code completely wrong. ? Please help

1条回答
霸刀☆藐视天下
2楼-- · 2019-07-19 04:16

The reason for the error is that your RemoteAttribute is calling the CheckBuildingName method of ConfigLocationControllerController. Assuming that you controller is actually named ConfigLocationController, then you attributes need to be

[Display(Name = "Building Name")] // use this attribute, not DisplayName
[Remote("CheckBuildingName", "ConfigLocation",ErrorMessage = "Building already exists!")]
public string buildingName { get; set; }

However your method also contains errors. You initialize a new instance of a model and then use the value of its buildingName property (which will be null) in your query so it will always return null. In additional, you should add a parameter for the value your ajax call is submitting rather than using Request.Form. You method can be simply

[HttpPost]
public JsonResult CheckBuildingName(string buildingName)
{
    bool exists = context.Buildings.Any(x => x.buildingName == buildingName && x.buildingActive);
    return Json(!exists, JsonRequestBehavior.AllowGet);
}

which will return true if there is no match, or false if there is, in which case the message you have defined in the attribute will be displayed in the view assuming you have included @Html.ValidationMessageFor(m => m.buildingName)

查看更多
登录 后发表回答