私のカスタムモデルの検証では、次のものがあります。
public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext){
var repository = DependencyResolver.Current.GetService(typeof(IContactRepository));
IContactRepository repo = repository as IContactRepository;
USRContact c = repo.GetContactByID(Convert.ToInt64(bindingContext.ValueProvider.GetValue("ContactID").AttemptedValue));
c.FormalName = bindingContext.ValueProvider.GetValue("FormalName").AttemptedValue;
if (!repo.IsValidFormalName(c.ContactID, c.FormalName))
{
var result = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
bindingContext.ModelState.AddModelError("FormalName", Resources.ErrorMsgs.FormalNameNotUnique);
return bindingContext.Model;
}
c.PreferredName = bindingContext.ValueProvider.GetValue("PreferredName").AttemptedValue;
c.Alias = bindingContext.ValueProvider.GetValue("Alias").AttemptedValue;
c.Pseudonym = bindingContext.ValueProvider.GetValue("Pseudonym").AttemptedValue;
c.GenderID = Convert.ToInt32(bindingContext.ValueProvider.GetValue("GenderID").AttemptedValue);
c.NationalityID = Convert.ToInt32(bindingContext.ValueProvider.GetValue("NationalityID").AttemptedValue);
c.ModifiedByID = Utilities.SessionUtil.Current.UserID;
c.ModifiedDate = DateTime.Now;
}
私のコントローラーは、次のようにしてこのモデル バインダーを呼び出します。
public ActionResult Update([ModelBinder(typeof(ModelBinder.ContactModelBinder))] USR.USRContact contact)
{
if (ModelState.IsValid)
{
repository.Update();
return View("~/Views/Shared/Contacts/ShowContactInfo.cshtml", repository.GetContactByID(contact.ContactID));
}
}
}
私のビューモデルには、正式な名前が必要であり、そのエイリアスは 60 文字未満である必要があることを示すデータ注釈が含まれています。モデル バインダーがそれを永続データ モデル (USRContact) に変換し、ビューがビューモデルを予期している場合、エラーを表示するにはどうすればよいですか?
ビュー モデルで検証エラーが発生した場合、コントローラーが永続データ モデルに変換されないようにする方法はありますか? データ オブジェクト内のすべてのモデル エラーをチェックして検証エラーを見つけたとしても、エラーが発生したテキスト ボックスの横にあるエラーが表示されたビューにユーザーを戻すにはどうすればよいでしょうか。
助けてくれてありがとう!サフリス