时间:2010-05-13 07:53:45

标签: asp.net-mvc validation asp.net-mvc-2

我有一个使用Depth属性在树中组织的对象列表:

public class Quota
{
    [Range(0, int.MaxValue, ErrorMessage = "Please enter an amount above zero.")]
    public int Amount { get; set; }

    public int Depth { get; set; }

    [Required]
    [RegularExpression("^[a-zA-Z]+$")]
    public string Origin { get; set; }

    // ... another properties with validation attributes
}

对于数据示例(金额 - 来源)

100 originA
200 originB
    50 originC
    150 originD

模型数据如下:

IList<Quota> model = new List<Quota>();
model.Add(new Quota{ Amount = 100, Depth = 0, Origin = "originA");
model.Add(new Quota{ Amount = 200, Depth = 0, Origin = "originB");
model.Add(new Quota{ Amount = 50,  Depth = 1, Origin = "originC");
model.Add(new Quota{ Amount = 150, Depth = 1, Orinig = "originD");

编辑列表

然后我使用Editing a variable length list, ASP.NET MVC 2-style来提升列表的编辑。

控制器操作 QuotaController.cs

public class QuotaController : Controller
{
    //
    // GET: /Quota/EditList
    public ActionResult EditList()
    {
        IList<Quota> model = // ... assigments as in example above;

        return View(viewModel);
    }

    //
    // POST: /Quota/EditList
    [HttpPost]
    public ActionResult EditList(IList<Quota> quotas)
    {
        if (ModelState.IsValid)
        {
            // ... save logic
            return RedirectToAction("Details");
        }
        return View(quotas); // Redisplay the form with errors
    }

    // ... other controller actions
}

查看 EditList.aspx

<%@ Page Title="" Language="C#" ... Inherits="System.Web.Mvc.ViewPage<IList<Quota>>" %>

...
<h2>Edit Quotas</h2>
<%=Html.ValidationSummary("Fix errors:") %>
<% using (Html.BeginForm()) { 
     foreach (var quota in Model)
     {
         Html.RenderPartial("QuotaEditorRow", quota);
     } %>
<% } %>
...

部分视图 QuotaEditorRow.ascx

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<Quota>" %>

<div class="quotas" style="margin-left: <%=Model.Depth*45 %>px">
    <% using (Html.BeginCollectionItem("Quotas")) { %>
        <%=Html.HiddenFor(m=>m.Id) %>
        <%=Html.HiddenFor(m=>m.Depth) %>


        <%=Html.TextBoxFor(m=>m.Amount, new {@class = "number", size = 5})%>
        <%=Html.ValidationMessageFor(m=>m.Amount) %>

        Origin:
        <%=Html.TextBoxFor(m=>m.Origin)%>
        <%=Html.ValidationMessageFor(m=>m.Origin) %>

        ...
    <% } %>
</div>

业务规则验证

  1. 如何实施业务规则验证配额金额应等于其嵌套配额金额的总和(例如,200 = 50 + 150)?

  2. 如果规则被破坏,我希望以红色突出显示适当的输入Html.TextBoxFor(m=>m.Amount) 例如,如果用户输入的不是200,而是201,则提交时应该为红色。

  3. 仅使用服务器验证。

  4. 非常感谢任何建议。

1 个答案:

答案 0 :(得分:1)

试试FluentValidation。它是一个非常简单和强大的验证框架,能够根据规则验证您的类。它还可以用于生成ClientSide JQuery Validators

验证对象的结果是ValidationFailue对象的列表。您可以迭代这些或将它们绑定到包含无序列表的转发器,该列表以红色格式化。

IList<ValidationFailure> failures = results.Errors;