1

1行内のチェックボックスにすべてのプロパティを表示する方法多くのプロパティを持つオブジェクト機能があり、これらのプロパティは動的に割り当てられ、ビューにハードコーディングしたくありません。だから、今私はこれらのようなものを持っています

@Html.CheckBoxFor(model => model.Features.IsRegistered, new { @disabled = "disabled" })
@Html.CheckBoxFor(model => model.Features.IsPhone, new { @disabled = "disabled" 

.... などなど

上記とまったく同じようにレンダリングする方法ですが、すべてのオブジェクトプロパティについて、これは可能ですか?ありがとう

4

1 に答える 1

0

私はこれを使っていくつかの限られたテストを行っただけですが、これがあなたが遊ぶことができる拡張メソッドの基本的な実装です:

public static class HtmlHelperExtensions
{
    public static MvcHtmlString CheckBoxesForModel(this HtmlHelper helper,
        object model)
    {
        if (model == null)
            throw new ArgumentNullException("'model' is null");

        return CheckBoxesForModel(helper, model.GetType());
    }

    public static MvcHtmlString CheckBoxesForModel(this HtmlHelper helper,
        Type modelType)
    {
        if (modelType == null)
            throw new ArgumentNullException("'modelType' is null");

        string output = string.Empty;
        var properties = modelType.GetProperties(BindingFlags.Instance | BindingFlags.Public);

        foreach (var property in properties)
            output += helper.CheckBox(property.Name, new { @disabled = "disabled" });

        return MvcHtmlString.Create(output);
    }
}

HTML属性をハードコーディングするのではなく、HTML属性も取得できるように拡張することもできますが、これで開始できます。

于 2012-08-07T21:20:59.693 に答える