剃刀视图表验证

时间:2020-09-23 16:01:33

标签: asp.net-mvc validation razor

我有一个元素表,用户在其中为每一行输入一个数字。我想验证用户输入的数字加起来等于100,并在输入数字时显示一条消息。

下面是我的观点

    <form asp-action="CreateResource">
        <table class="table table-bordered table-condensed table-hover" id="tbFunds">
            <thead>
                <tr>
                    <th>
                        Fund Name
                    </th>
                    <th>
                        Percentage
                    </th>
                </tr>
            </thead>
            @for (int i = 0; i < Model.FundItems.Count; i++)
            {
                <tr>
                    <td>
                        @Html.Label(Model.FundItems[i].FundName)
                    </td>
                    <td>
                        @Html.HiddenFor(x => Model.FundItems[i].FundId)
                        @Html.EditorFor(x => Model.FundItems[i].Percentage)
                    </td>
                </tr>
            }
        </table>
        <div class="form-group">
            <input type="submit" value="Create" class="btn btn-primary" />
        </div>
    </form>

还有我的模特

public class CreateResource
{
    [Required]
    [StringLength(100)]
    [Display(Name = "Resource Name")]
    public string ResourceName { get; set; }        
    public List<CreateResourceFundItem> FundItems { get; set; }
}

public class CreateResourceFundItem
{
    public Guid FundId { get; set; }

    [Display(Name = "Fund Name")]
    public string FundName { get; set; }

    [Required]
    [Display(Name = "Percentage")]
    public int Percentage { get; set; }
} 

我尝试像这样使用DataAnnotationExtensions.EqualTo属性,但是它不起作用。

public class CreateResource
{
    [Required]
    [StringLength(100)]
    [Display(Name = "Resource Name")]
    public string ResourceName { get; set; }        
    public List<CreateResourceFundItem> FundItems { get; set; }

    [EqualTo("Total", ErrorMessage ="Percentages must add up to 100")]
    public int ItemsTotal { get { return FundItems.Sum(x => x.Percentage); } }
    public int Total { get { return 100; } }
}

您认为解决此问题的最佳方法是什么?

0 个答案:

没有答案