【发布时间】:2010-05-13 07:53:45
【问题描述】:
我有一个使用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>
业务规则验证
如何实现业务规则验证: 配额数量应该等于其嵌套配额数量的总和(例如,200 = 50 + 150)?
如果规则被破坏,我希望适当的输入
Html.TextBoxFor(m=>m.Amount)以红色突出显示。 例如,如果用户输入的不是 200,而是 201 - 提交时它应该是红色的。仅使用服务器验证。
非常感谢您的建议。
【问题讨论】:
标签: asp.net-mvc validation asp.net-mvc-2