Многолетний читатель, первый постер.
Я использую ASP MVC 2 и удаленную проверку. У меня есть модель под названием PersonVM, от которой наследуются AddPersonVM и EditPersonVM. Это сделано для того, чтобы я мог использовать один пользовательский элемент управления для обработки большей части пользовательского интерфейса, который одинаков для обеих подклассовых моделей.
</p>
<pre><code>/// <summary>
/// This class handles adding and editing people.
/// </summary>
[MustHaveAtLeastOneOf("HomePhoneNumber", "CellPhoneNumber", ErrorMessage="At least one of the phone numbers must be filled in.")]
public abstract class PersonVM : WebViewModel
{
#region Reference (for Binding)
/// <summary>
/// Provides a list of person types, e.g. Teacher, Student, Parent.
/// </summary>
public IEnumerable<PersonType> ListOfPersonTypes {
get {
if (_listOfPersonTypes == null) {
_listOfPersonTypes = Data.PersonTypes
.Where(pt => pt.OrganizationID == ThisOrganization.ID || pt.OrganizationID == null)
.OrderBy(pt => pt.Name).ToArray();
}
return _listOfPersonTypes;
}
}
private IEnumerable<PersonType> _listOfPersonTypes = null;
/// <summary>
/// Provides a list of schools the person can belong to.
/// </summary>
public IEnumerable<School> ListOfSchools {
get {
if (_listOfSchools == null) {
_listOfSchools = Data.Schools
.Where(s =>
(s.OrganizationID == ThisOrganization.ID || s.OrganizationID == null) // TODO
&& s.Deleted == false
)
.OrderBy(s => s.Name);
}
return _listOfSchools;
}
}
private IEnumerable<School> _listOfSchools = null;
/// <summary>
/// Provides a list of contact types, e.g. Home phone, email.
/// </summary>
public IEnumerable<ContactType> ListOfContactTypes {
get {
if (_listOfContactTypes == null) {
_listOfContactTypes = Data.ContactTypes
.OrderBy(ct => ct.Name);
}
return _listOfContactTypes;
}
}
private IEnumerable<ContactType> _listOfContactTypes = null;
/// <summary>
/// Provides a list of genders.
/// </summary>
public IEnumerable<string> Genders {
get {
return new string[] { null, "Male", "Female" };
}
}
/// <summary>
/// Returns a list of US states.
/// </summary>
public List<StaticData.USState> ListOfUSStates {
get {
return StaticData.USStates;
}
}
#endregion
/// <summary>
/// Represents the current person being edited.
/// </summary>
public Person CurrentPerson { get; set; }
#region Abstracted Required Fields
/*
* This is done, since address information, DOB
* are not required on the panel, but are required fields here.
* I tried implementing an interface called IPersonAddressRequired
* with this information in it, but it didn't work. Additionally,
* only one instance of [MetadataType] is allowed on a class,
* so that didn't work either.
*/
[Required]
[StringLength(100)]
public string Address {
get { return CurrentPerson.Address; }
set { CurrentPerson.Address = value; }
}
[StringLength(100)]
public string Address2 {
get { return CurrentPerson.Address2; }
set { CurrentPerson.Address2 = value; }
}
[Required]
[StringLength(50)]
public string City {
get { return CurrentPerson.City; }
set { CurrentPerson.City = value; }
}
[Required]
[StringLength(50)]
public string State {
get { return CurrentPerson.State; }
set { CurrentPerson.State = value; }
}
[Required]
[StringLength(50)]
public string Zip {
get { return CurrentPerson.Zip; }
set { CurrentPerson.Zip = value; }
}
[DataType(DataType.Date)]
[Required]
public DateTime? DOB {
get { return CurrentPerson.DOB; }
set { CurrentPerson.DOB = value; }
}
[Required]
public string Gender {
get { return CurrentPerson.Gender; }
set { CurrentPerson.Gender = value; }
}
#endregion
#region Abstracted Contact Methods
/// <summary>
/// When adding someone, this represents the phone number contact record.
/// </summary>
[Display(Name = "Home Phone Number")]
[DisplayName("Home Phone Number")]
[USPhoneNumber]
//[Required]
public string HomePhoneNumber { get; set; }
/// <summary>
/// When adding someone, this represents the phone number contact record.
/// </summary>
[Display(Name = "Cell Phone Number")]
[DisplayName("Cell Phone Number")]
[USPhoneNumber]
//[Required]
public string CellPhoneNumber { get; set; }
/// <summary>
/// When adding someone, this represents the email address contact record.
/// </summary>
[Display(Name = "Email Address")]
[DisplayName("Email Address")]
[Required]
[UniqueEmailAddress(ErrorMessage="The email address was already found in our system, please sign in or use another email.")]
[Email(ErrorMessage="The email address specified isn't an email address.")]
public string EmailAddress { get; set; }
#endregion
//////////////////////////////
/// <summary>
/// Sets the picture to be uploaded.
/// </summary>
public byte[] PictureData { get; set; }
/// <summary>
/// One of 'keep', 'remove', 'replace'.
/// </summary>
public string PictureAction { get; set; }
}
У меня есть 2 модели, унаследованные от этой модели, AddPersonVM и EditPersonVM. Каждый реализует, как они обрабатывают отправку изменений немного по-своему.
[UniqueEmailAddress] - это мой RemoteAttribute, который проверяет существующий адрес электронной почты и то, с чем у меня проблема.
Это прекрасно работает при добавлении кого-либо, но при редактировании существующего человека уже сохраненный адрес электронной почты существует в системе членства, поэтому он не проходит проверку. Я хотел бы сохранить исходное значение значения свойства и исключить его из проверки IsValid.
Мой код:
</p>
<pre><code>/// <summary>
/// Checks to be sure that an entered email address is unique.
/// </summary>
public class UniqueEmailAddressAttribute : RemoteAttribute
{
/// <summary>
/// Returns true if the email address specified is currently in use.
/// </summary>
/// <param name="emailAddress"></param>
/// <returns></returns>
public static bool IsEmailAddressInUse(string emailAddress) {
return (Membership.FindUsersByEmail(emailAddress).Count != 0);
}
///////////////////////////
public UniqueEmailAddressAttribute() : base("UniqueEmailAddress", "RemoteValidation", "emailAddress") { }
///////////////////////////
public override bool IsValid(object value) {
// If value is null, return true, since a [Required] attribute handles required values.
if (value == null)
return true;
// Value must be a string.
if (!(value is string))
return false;
// We're not checking the validity of the email address here,
// the [EmailAddress] attribute handles that for us.
// Check the email's uniqueness.
return !IsEmailAddressInUse((string)value);
}
}
Что бы я хотел иметь:
///
/// Checks to be sure that an entered email address is unique.
///
public class UniqueEmailAddressAttribute : RemoteAttribute
{</p>
<p>string OriginalValue = null;</p>
<pre><code> /// <summary>
/// Returns true if the email address specified is currently in use.
/// </summary>
/// <param name="emailAddress"></param>
/// <returns></returns>
public static bool IsEmailAddressInUse(string emailAddress) {
return (Membership.FindUsersByEmail(emailAddress).Count != 0);
}
///////////////////////////
public UniqueEmailAddressAttribute() : base("UniqueEmailAddress", "RemoteValidation", "emailAddress") {
OriginalValue = value Found using reflection or something;
}
///////////////////////////
public override bool IsValid(object value) {
// If value is null, return true, since a [Required] attribute handles required values.
if (value == null)
return true;
// Value must be a string.
if (!(value is string))
return false;
// We're not checking the validity of the email address here,
// the [EmailAddress] attribute handles that for us.
if ((string)value == OriginalValue)
return true;
// Check the email's uniqueness.
return !IsEmailAddressInUse((string)value);
}
}
Есть идеи? На данный момент я могу добавить свойство EmailAddress по отдельности как в AddPersonVM, так и в EditPersonVM, вывести поле из моего представления usercontrol и добавить в оба представления, а также удалить атрибут при редактировании, но тогда никто не помешает редактировать свою учетную запись, чтобы иметь любой адрес электронной почты они хотят. Мне все равно, требуется ли отражение, чтобы прочитать исходное значение, это круто.
Заранее спасибо! - Derreck