.net - ASP.NET Core MVC - 使用 IClientModelValidator 创建 RequiredIf 属性
问题描述
我正在尝试使用 IClientModelValidator 在 Core 2.0 中创建一个 RequiredIf 属性。我在这里查看了许多线程,试图为自己解决这个问题,但由于某种原因,它没有按预期工作。
基本上,我想要它,以便如果属性 EmpTypeSelected 等于“Contractor”,我想要求用户输入 CompanyName 的值。
这是我到目前为止所拥有的。
public class UserViewModel
{
[Display(Name = "Company Name")]
[EmpTypeCompanyRequired("EmpTypeSelected", ErrorMessage = "Please enter a company name.")]
public string CompanyName { get; set; }
public IEnumerable<SelectListItem> EmpTypes { get; set; }
[Required(ErrorMessage = "You must select an Employee Type")]
public string EmpTypeSelected { get; set; }
[Display(Name = "Employee Type")]
public string EmpTypeName { get; set; }
}
public class EmpTypeCompanyRequiredAttribute : ValidationAttribute, IClientModelValidator
{
private readonly string _comparisonProperty;
public EmpTypeCompanyRequiredAttribute(string comparisonProperty)
{
_comparisonProperty = comparisonProperty;
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
ErrorMessage = ErrorMessageString;
var contractorTypeValue = "Contractor";
var property = validationContext.ObjectType.GetProperty(_comparisonProperty);
if (property == null)
throw new ArgumentException("Property with this name not found");
var comparisonValue = (string) property.GetValue(validationContext.ObjectInstance);
if (contractorTypeValue == comparisonValue)
return new ValidationResult(ErrorMessage);
return ValidationResult.Success;
}
public void AddValidation(ClientModelValidationContext context)
{
var error = FormatErrorMessage(context.ModelMetadata.GetDisplayName());
MergeAttribute(context.Attributes, "data-val", "true");
MergeAttribute(context.Attributes, "data-val-error", error);
}
private bool MergeAttribute(IDictionary<string, string> attributes, string key, string value)
{
if (attributes.ContainsKey(key))
{
return false;
}
attributes.Add(key, value);
return true;
}
}
视图看起来像:
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
<div class="form-group">
@Html.LabelFor(model => model.EmpTypeName, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.DropDownListFor(model => model.EmpTypeSelected, new SelectList(@Model.EmpTypes, "Value", "Text", Model.EmpTypeSelected), new { id = "EmpTypeSelected", @class = "form-control" })
@Html.ValidationMessageFor(model => model.EmpTypeSelected, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.CompanyName, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.CompanyName, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.CompanyName, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
}
我是否缺少某些东西以便进行客户端验证?
任何想法都非常感谢!
解决方案
在您的控制器中尝试类似:
public ActionResult Index(UserViewModel model)
{
if (!ModelState.IsValid)
{
// There was a validation error => redisplay the view so
// that the user can fix it
return View(model);
}
else
{
//Return View/Or Redirect
}
}
索引.cshtml
@using (Html.BeginForm())
{
@Html.EditorFor(x => x.Query)
@Html.ValidationMessageFor(x => x.Query)
<button type="submit">Search</button>
}
推荐阅读
- javascript - DeprecationWarning: Buffer() 当我尝试在可视代码上安装扩展时。请问我该如何解决这个问题
- postgresql - Ktor 无法在 Postgres 中创建表
- snowflake-cloud-data-platform - 是否有任何内置函数或快速方法来获取存储过程或函数中使用的底层对象名称?
- angular - TypeError:无法设置未定义的属性
- java - Spring Data JPA(Spring Boot 2)中的多个表连接
- javascript - 错误 [ERR_STREAM_WRITE_AFTER_END]:结束后写入,http 服务器 node.js
- d - 转换 C "srand(time(NULL));" 转D语言
- javascript - 当鼠标不移动或鼠标进入其他容器 React js 时如何停止轨迹
- asp.net - 网格中的边框显示
- python - 在 SQL 帮助中迭代查询 + 忽略案例