質問

私の見解で定義されているセクションドロップダウンリストを処理するために、独自のカスタムモデルバインダーを作成しました。

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()));

    ...
}

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

誰かがこれを行う方法を教えてくれたら感謝します。ありがとう

役に立ちましたか?

解決

問題が解決する問題:

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

この問題は、セクションが整数であることを中心に解決しているようです。文字列に変換すると、すべてが正常に機能します。お役に立てれば。

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top