我会以不同的方式对待他们。我建议我们有两个不同的地址模型并将它们放入一个视图模型中。
让我们为您的Address
类指定一些virtual
关键字,以便我们可以覆盖类属性。
public class Address
{
[DisplayName("Address")]
public virtual string StreetAddress { get; set; }
[DisplayName("City")]
public virtual string City { get; set; }
[DisplayName("State")]
public virtual string SelectedState { get; set; }
[DataType(DataType.PostalCode)]
[RegularExpression(@"^\d{5}$|^\d{5}-\d{4}$", ErrorMessage="The postal code should be in the format 00000 or 00000-0000")]
[DisplayName("Zip")]
public virtual string Zip { get; set; }
}
现在让我们创建一个继承我们的 Address 类的新模型。
public class MandatoryAddress : Address
{
[Required]
public override string StreetAddress { get; set; }
[Required]
public override string City { get; set; }
[Required]
public override string SelectedState { get; set; }
[Required]
public override string Zip { get; set; }
}
现在让我们创建我们的viewModel
public class MyFormViewModel
{
public MandatoryAddress StreetAddress { get; set; }
public Address MailingAddress { get; set; }
}
视图可能如下所示
@{
ViewBag.Title = "My Sample Form";
}
@model TestApp.Models.MyFormViewModel
<h2>@ViewBag.Title</h2>
@using (Html.BeginForm())
{
<fieldset>
<legend>Street Address</legend>
<div>
@Html.LabelFor(x => x.StreetAddress.StreetAddress)
@Html.EditorFor(x => x.StreetAddress.StreetAddress)
@Html.ValidationMessageFor(x => x.StreetAddress.StreetAddress)
</div>
<div>
@Html.LabelFor(x => x.StreetAddress.City)
@Html.EditorFor(x => x.StreetAddress.City)
@Html.ValidationMessageFor(x => x.StreetAddress.City)
</div>
<div>
@Html.LabelFor(x => x.StreetAddress.SelectedState)
@Html.EditorFor(x => x.StreetAddress.SelectedState)
@Html.ValidationMessageFor(x => x.StreetAddress.SelectedState)
</div>
<div>
@Html.LabelFor(x => x.StreetAddress.Zip)
@Html.EditorFor(x => x.StreetAddress.Zip)
@Html.ValidationMessageFor(x => x.StreetAddress.Zip)
</div>
</fieldset>
<fieldset>
<legend>Mailing Address</legend>
<div>
@Html.LabelFor(x => x.MailingAddress.StreetAddress)
@Html.EditorFor(x => x.MailingAddress.StreetAddress)
@Html.ValidationMessageFor(x => x.MailingAddress.StreetAddress)
</div>
<div>
@Html.LabelFor(x => x.MailingAddress.City)
@Html.EditorFor(x => x.MailingAddress.City)
@Html.ValidationMessageFor(x => x.MailingAddress.City)
</div>
<div>
@Html.LabelFor(x => x.MailingAddress.SelectedState)
@Html.EditorFor(x => x.MailingAddress.SelectedState)
@Html.ValidationMessageFor(x => x.MailingAddress.SelectedState)
</div>
<div>
@Html.LabelFor(x => x.MailingAddress.Zip)
@Html.EditorFor(x => x.MailingAddress.Zip)
@Html.ValidationMessageFor(x => x.MailingAddress.Zip)
</div>
</fieldset>
<div>
<input type="submit" />
</div>
}
控制器可能如下所示:
public class FormController : Controller
{
//
// GET: /Form/
[HttpGet]
public ActionResult Index()
{
MyFormViewModel viewModel = new MyFormViewModel();
return View(viewModel);
}
[HttpPost]
public ActionResult Index(MyFormViewModel viewModel)
{
return View(viewModel);
}
}
奖励经验值:
另一种方法(更复杂但可以说“更好”)是创建您自己的自定义[Required]
属性,您可以将其应用于类(即StreetAddress
)。该属性必须遍历类的每个属性并应用一个[Required]
属性。