c# - 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 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>
解决方案
问题似乎来自内部声明的控制器名称,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; }
相关问题:
推荐阅读
- ios - SwiftUI - 更改默认选择器项目高度
- mysql - 如何在sequelize中分组并获取相关数据数组
- java - 如何从Java中的函数访问变量?
- r - gsub 提取字符串
- python - 我的程序运行但我没有在控制台上收到反馈
- cuda - 分析一个CUDA矩阵加法代码,使用nvprof:代码API配置文件,内核没有
- python - Python/Pandas/Numpy 问题:如何在保留第四列名称的同时堆叠/合并三列
- perl - 在 Perl 中使用 require
- vb.net - 根据 DataGridView 单元格值更新 ComboBox 选择?
- python-3.x - 如何处理sklearn中不是整数的数据