1

ビューで次のように定義された 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()));

    ...
}

これは適切に検証され、モデルが更新されるとセクションの正しい値が割り当てられますが、別のプロパティが検証されない場合は正しい値が選択されません。

誰かがこれを行う方法を教えていただければ幸いです。ありがとう

4

1 に答える 1

0

次のように言って問題を解決しました。

Html.DropDownListFor(m => m.Category.Section, new SelectList(Model.Sections.Select(s => new { Text = s.SectionName, Value = s.SectionID.ToString() }), "Value", "Text"), "-- Please Select --") 

この問題は、SectionID が整数になると解決するようです。それを文字列に変換すると、すべて正常に動作します。お役に立てれば。

于 2010-09-05T17:33:14.990 に答える