【问题标题】:Error when trying to set up custom validation in MVC 5尝试在 MVC 5 中设置自定义验证时出错
【发布时间】:2018-12-12 20:35:47
【问题描述】:

尝试使用 DataAnnotations 在模型中提交具有自定义验证集的表单时,我收到错误消息“找不到路径 '/ItemController/IsAssetAvailable' 的控制器或未实现 IController”。

控制器布局:

控制器代码:

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);
            }
        }
    }

数据注释:

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

查看:

<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-mvc asp.net-mvc-5


    【解决方案1】:

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

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

    你正在使用的RouteAttributewith 2 overloads

    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; }
    

    相关问题:

    Error based on Remote Validation in mvc

    【讨论】:

    • 这正是问题所在,谢谢!解释也很好。
    猜你喜欢
    • 2020-08-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-15
    • 1970-01-01
    • 2019-02-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多