ビューで次のように定義された Section DropDownList を処理するために、独自のカスタム モデル バインダーを作成しました。
Html.DropDownListFor(m => m.Category.Section, new SelectList(Model.Sections, "SectionID", "SectionName"), "-- Please Select --")
そして、ここに私のモデルバインダーがあります:
public class SectionModelBinder : DefaultModelBinder
{
public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
var value = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
if (bindingContext.ModelType.IsAssignableFrom(typeof(Section)) && value != null)
{
if (Utilities.IsInteger(value.AttemptedValue))
return Section.GetById(Convert.ToInt32(value.AttemptedValue));
else if (value.AttemptedValue == "")
return null;
}
return base.BindModel(controllerContext, bindingContext);
}
}
今私のコントローラ内で私は言うことができます:
[HttpPost]
public ActionResult Create(FormCollection collection)
{
var category = new Category();
if (!TryUpdateModel(category, "Category")
return View(new CategoryForm(category, _sectionRepository().GetAll()));
...
}
これは適切に検証され、モデルが更新されるとセクションの正しい値が割り当てられますが、別のプロパティが検証されない場合は正しい値が選択されません。
誰かがこれを行う方法を教えていただければ幸いです。ありがとう