我正在尝试使用IClientModelValidator在Core 2.0中创建RequiredIf属性。我在这里回顾了许多线程,试图自己解决它,但是由于某种原因,它没有按预期工作。
基本上,我想要这样,如果属性EmpTypeSelected等于“承包商”,我希望要求用户输入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>
}
是否缺少我要进行客户端验证的内容?
任何想法都将不胜感激!
答案 0 :(得分:0)
在您的控制器中尝试类似的操作:
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
}
}
Index.cshtml
@using (Html.BeginForm())
{
@Html.EditorFor(x => x.Query)
@Html.ValidationMessageFor(x => x.Query)
<button type="submit">Search</button>
}