簡體   English   中英

ASP.NET Core MVC-使用IClientModelValidator創建RequiredIf屬性

[英]ASP.NET Core MVC - Creating a RequiredIf Attribute using IClientModelValidator

我正在嘗試使用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>
}

是否缺少我要進行客戶端驗證的內容?

任何想法都將不勝感激!

在您的控制器中嘗試以下操作:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM