ASP.NET MVC- IDフィールド用のカスタムモデルバインダー
-
30-09-2019 - |
質問
私は次のエンティティを持っています:
public class Category
{
public virtual int CategoryID { get; set; }
[Required(ErrorMessage = "Section is required")]
public virtual Section Section { get; set; }
[Required(ErrorMessage = "Category Name is required")]
public virtual string CategoryName { get; set; }
}
public class Section
{
public virtual int SectionID { get; set; }
public virtual string SectionName { get; set; }
}
ここで、私の追加カテゴリビュー内に、セクションIDを入力するテキストボックスがあります。
<%= Html.TextBoxFor(m => m.Section.SectionID) %>
次のロジックを持つようにカスタムモデルバインダーを作成したいと思います。
モデルキーがIDで終了し、値(値がテキストボックスに挿入された)を持っている場合、親オブジェクト(この例のセクション)をセクションに設定します。GetByID(入力)
これはしばらく私を困惑させてきたので、ここで助けてくれて本当に感謝しています。ありがとう
解決 2
Dave Thiebenが投稿したソリューションを使用して、次のことを思いつきました。
public class CustomModelBinder : DefaultModelBinder
{
public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
var value = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
if (bindingContext.ModelType.Namespace.EndsWith("Models.Entities") && value != null && (Utilities.IsInteger(value.AttemptedValue) || value.AttemptedValue == ""))
{
if (value.AttemptedValue != "")
return Section.GetById(Convert.ToInt32(value.AttemptedValue));
else
return null;
}
else
return base.BindModel(controllerContext, bindingContext);
}
}
これはうまく機能しますが、フォームが戻ってドロップダウンリストを使用したときに適切な値を選択しません。理由はわかりますが、これまでのところ、それを修正しようとする試みは無駄でした。あなたが助けることができればもう一度感謝します。
他のヒント
モデルバインダーを投稿しました この質問 それは、IREPOSITORYを使用して、外国の鍵が存在する場合に埋めます。目的に合わせて変更できます。
所属していません StackOverflow