TryUpdateModel を使用して、DataAnnotations を使用して asp.NET MVC 2 RC2 のモデルに検証を追加しようとしています。
var user = UserManager.Find(id);
this.TryUpdateModel<IProvisioningObject>(user, form.ToValueProvider());
これによりモデルが更新されますが、検証は呼び出されません。フォーム値プロバイダーを使用せずに、(検証メタデータを持つ) ProvisioningObject を直接使用して、TryUpdateModel (ユーザーの直接型) も使用してみましたが、役に立ちませんでした。
例をグーグルで検索すると、パラメーターを介してバインドすることで DataAnnotations を使用する方法しか得られません
public ActionResult Update(User user)
更新シナリオが嫌いです。
ヒントや解決策はありますか?
編集 私のオブジェクトは、WCF サービスから自動生成されたオブジェクトです。
DataAnnotations を追加できるようにパーシャルを作成しました。どうやら継承をサポートしていないため、TryUpdateModel を 3 回呼び出します。これは、DataAnnotations の問題でもあると思います。ProvisioningObject の検証属性を指定すると、バインディングはそのような継承されたものを探しません。
[MetadataType(typeof(ProvisioningObjectMetadata))]
public partial class ProvisioningObject : IProvisioningObject
{
public string DisplayNameInvariant { get { return string.IsNullOrEmpty(this.DisplayName) ? this.Name : this.DisplayName; } }
}
[MetadataType(typeof(UserMetadata))]
public partial class User : IUser
{
}
public class ProvisioningObjectMetadata
{
[DisplayName("Country")]
public string CountryIsoCode { get; set; }
[Required(ErrorMessageResourceType = typeof(Properties.Validation), ErrorMessageResourceName = "DisplayNameIsRequired")]
[TempValidator]
public string DisplayName { get; set; }
}
public class UserMetadata
{
[DisplayName("Username")]
public string Name { get; set; }
}
// Controller action
public ActionResult Update(string id, FormCollection form)
{
var user = UserManager.Find(id);
this.TryUpdateModel<IUser>(user.User, form.ToValueProvider());
this.TryUpdateModel<IPerson>(user.User, form.ToValueProvider());
this.TryUpdateModel<IProvisioningObject>(user.User, form.ToValueProvider());
if (ModelState.IsValid) // always true
{
return Redirect;
}
else
{
return View();
}
}
UserMetadata に DisplayName のメタデータを追加すると、期待どおりに動作しますが、それは非常に冗長に思えます。また、TryUpdateModel が適切に動作するように、継承したすべてのインターフェイスをコピーして貼り付ける必要があることも意味します。
検証属性をコピーして継承されたクラスに貼り付ける必要のない方法を探していると思います。