我似乎无法弄清楚如何验证将部分 ViewModel 作为子对象的 ViewModel 的部分视图片段。这是我最低级别的部分,它总是作为其他表单标签中的部分视图使用:
namespace MVC3App.ViewModels
{
public class Payment : IValidatableObject
{
public decimal Amount { get; set; }
public int CreditCardNumber { get; set; }
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
if (Amount < 20)
yield return new ValidationResult("Please pay more than $20", new string[] { "Amount" });
}
}
}
这是包含它的“主要”视图模型:
namespace MVC3App.ViewModels
{
public class NewCustomerWithPayment :IValidatableObject
{
public string Name { get; set; }
public int Age { get; set; }
public ViewModels.Payment PaymentInfo { get; set; }
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
if (Age < 18)
yield return new ValidationResult("Too young.", new string[] { "Age" });
}
}
}
对于 NewCustomerWithPayment 的视图,我有这个:
@model MVC3App.ViewModels.NewCustomerWithPayment
@using (Html.BeginForm()) {
@Html.ValidationSummary(true)
<fieldset>
<legend>NewCustomerWithPayment</legend>
<div class="editor-label">
@Html.LabelFor(model => model.Name)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Name)
@Html.ValidationMessageFor(model => model.Name)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.Age)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Age)
@Html.ValidationMessageFor(model => model.Age)
</div>
</fieldset>
@Html.Partial("Payment")
<p><input type="submit" value="Create" /></p>
}
并且部分视图“付款”总是在另一个 Html.Beginform 标记中呈现,它只有这个:
@model MVC3App.ViewModels.Payment
<h2>Payment</h2>
<fieldset>
<legend>Payment</legend>
<div class="editor-label">
@Html.LabelFor(model => model.Amount)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Amount)
@Html.ValidationMessageFor(model => model.Amount)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.CreditCardNumber)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.CreditCardNumber)
@Html.ValidationMessageFor(model => model.CreditCardNumber)
</div>
</fieldset>
我的问题是我无法让“付款”视图模型上的验证工作。任何有使用 IValidatableObject 经验的人都可以在呈现为部分视图的 ViewModel 上加入并给我一个有效的验证模式吗?如果必须,我可以在没有 JavaScript 验证的情况下生活。