ASP.NET MVC モデル バインディングでこの問題が発生しました。国の子オブジェクトを持つ住所オブジェクトがあります。ただし、国名にはオートコンプリートを使用しています。したがって、私の見解では、次のようなものがあります。
@Html.EditorFor(model => model.Country)
そして、ここにカスタムバインダーを書きました:
public class CountryBinder : IModelBinder
{
public CountryBinder(DataContext db)
{
this.Db = db;
}
protected DataContext Db { get; set; }
public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
var countryName = controllerContext.HttpContext.Request[bindingContext.ModelName];
var result = Db.Countries.SingleOrDefault(
country => country.EnglishShortName.Equals(countryName) | country.Translation_NL.Equals(countryName));
return result;
}
}
データ コンテキストは次のように挿入されます。
kernel.Bind<IDBContext>().To<DataContext>().InRequestScope();
コントローラーは次のようになります。
var model = this.participationRepository.Single(p => p.Id == participation.Id);
if (!participation.IsCancelled)
{
this.TryUpdateModel(model);
等...
保存するたびに、新しい国が作成され、バインダーで見つかった国の正確な仕様が使用されますが、新しい ID が使用されます。手がかりはありますか?