我在这个项目中的一些表单中使用了复合视图模型的模式。它运作得很好。
在本例中,我有一个 VendorAddress 视图模型。我在这个项目的几个地方使用了 Address(es),因此我制作了可以重复使用的 Address 视图模型对象。然后我决定要对州代码和邮政编码进行非常彻底的检查,因此我决定尝试使用远程验证并根据数据库中存储的一组表检查州和邮政编码。
问题是我没有将我要求的字段(在本例中为“州”和“邮政编码”)的值返回到远程操作方法。我相信这是因为 MVC 框架对输入的 id 的复合类型或子类型进行了名称修改,在本例中,它使用“Address_Line1”、“Address_State”和“Address_PostalCode”等名称。
最终我的问题是,是否有一种方法可以从基本视图模型对象中关闭前置的“Address_”,以便 MVC 框架可以在表单发布后将其放入对象中?
public class AddressViewModel
{
[ScaffoldColumn(false)]
public int AddressId { get; set; }
[Required(ErrorMessage = "Please enter the first address line")]
public string Line1 { get; set; }
public string Line2 { get; set; }
public string Line3 { get; set; }
[Required(ErrorMessage = "Please enter a city name")]
public string City { get; set; }
[Required(ErrorMessage = "Please enter a state 2 letter code")]
[StringLength(2)]
[Remote("CheckState", "Validation", AdditionalFields = "PostalCode")]
public string State { get; set; }
[Required(ErrorMessage = "Please enter a postal code")]
[Remote("CheckZip", "Validation", AdditionalFields = "State")]
[Display(Name = "Zip / Postal Code")]
public string PostalCode { get; set; }
public string Country { get; set; }
}
public class VendorContactViewModel
{
public int VedorContactId { get; set; }
public int ContactVendorId { get; set; }
public int ContactId { get; set; }
[Required]
[Display(Name = "Contact Type")]
public byte ContactTypeId { get; set; }
public string ContactType { get; set; }
[Required]
[Display(Name = "Contact Info")]
public string ContactInfo { get; set; }
[Display(Name = "Contact Label")]
public string ContactLabel { get; set; }
public IEnumerable<SelectListItem> ContactTypes { get; set; }
}
然后在渲染后的表单中它看起来像这样:
<input type="text" value="" size="2" name="Address.State" maxlength="2" id="Address_State"
data-val-required="Please enter a state 2 letter code" data-val-remote-url="/Validation/CheckState"
data-val-remote-additionalfields="*.State,*.PostalCode" data-val-remote="&#39;State&#39; is invalid."
data-val-length-max="2" data-val-length="The field State must be a string with a maximum length of 2."
data-val="true" class="input-validation-error">
我收到远程调用,但参数“State”和“PostalCode”中没有任何内容,因此不显眼的例程正在触发,但我认为它不知道在哪里查找数据,即使我在提到的字段中输入了一些内容。正如您在渲染的代码中看到的 id="Address_State" 和 data-val-remote-additionalfields=".State,。邮政编码”
感谢您的时间和努力,
Irv