首页 > 解决方案 > Error when trying to set up custom validation in MVC 5

问题描述

I get the error message "The controller for path '/ItemController/IsAssetAvailable' was not found or does not implement IController" when trying to submit my form that has the custom validation set for it in the model using DataAnnotations.

Controller Layout:

Controller design

Controller Code:

public ActionResult IsAssetAvailable(string Asset_Tag_Nbr)
    {
        using (db)
        {
            try
            {
                var asset = db.Items.Single(i => i.Asset_Tag_Nbr == Asset_Tag_Nbr);
                return Json(false, JsonRequestBehavior.AllowGet);
            }
            catch (Exception)
            {
                return Json(true, JsonRequestBehavior.AllowGet);
            }
        }
    }

Data Annotations:

[Display(Name = "Asset Tag #")]
[Remote("IsAssetAvailable", "ItemController", ErrorMessage = "Asset # already exists.")]
public string Asset_Tag_Nbr { get; set; }

View:

<div class="form-group col-sm-4">
     @Html.LabelFor(model => model.Asset_Tag_Nbr, new { @class = "control-label col-md-12" })
     <div class="col-md-10">
         @Html.EditorFor(model => model.Asset_Tag_Nbr, new { htmlAttributes = new { @class = "form-control" } })
         @Html.ValidationMessageFor(model => model.Asset_Tag_Nbr)
     </div>
</div>

标签: c#asp.net-mvcasp.net-mvc-5

解决方案


问题似乎来自内部声明的控制器名称,RemoteAttribute如下所示:

[Remote("IsAssetAvailable", "ItemController", ErrorMessage = "Asset # already exists.")]
public string Asset_Tag_Nbr { get; set; }

您正在使用RouteAttribute 2 个重载

public RemoteAttribute (string action, string controller)

参数是控制器名称,包含对应的controller动作方法名称,不带Controller后缀。因此,您应该使用RouteAttribute如下示例的参数:

[Display(Name = "Asset Tag #")]
[Remote("IsAssetAvailable", "Item", ErrorMessage = "Asset # already exists.")]
public string Asset_Tag_Nbr { get; set; }

相关问题:

基于 mvc 中的远程验证的错误


推荐阅读