0

mvc3 アプリケーションに次のモデルがあります。Weight と Quantity にマップする 2 つのラジオ ボタンをビューに表示したいと考えています (これらはデータベースのビット フィールドです)。

public Unit()
    {
        this.OrderLineQuantity = new HashSet<OrderLine>();
        this.OrderLineWeight = new HashSet<OrderLine>();
    }

    public int ID { get; set; }
    public System.Guid UserId { get; set; }
    public string ShortDescription { get; set; }
    public string Desciption { get; set; }
    public System.DateTime AddDate { get; set; }
    public System.DateTime UpdateDate { get; set; }
    public Nullable<bool> Weight { get; set; }
    public Nullable<bool> Quantity { get; set; }

    public virtual ICollection<OrderLine> OrderLineQuantity { get; set; }
    public virtual ICollection<OrderLine> OrderLineWeight { get; set; }

強く型付けされたカミソリ ビューには、(簡略化された) 以下があります。

@using (Html.BeginForm()) {
@Html.ValidationSummary(true)
<fieldset>
    <legend>Unit</legend>

    <table>
        <tr>
            <td>@Html.LabelFor(model => model.Weight)</td>
            <td>@Html.LabelFor(model => model.Quantity)</td>
        </tr>
        <tr>
            <td>
                @Html.RadioButton("unitType", "false", "Weight")
                @Html.ValidationMessageFor(model => model.Weight)
            </td>
            <td>
                @Html.RadioButton("unitType", "false", "Quantity")
                @Html.ValidationMessageFor(model => model.Quantity)
            </td>
        </tr>
    </table>
    <p>
        <input type="submit" value="Create" />
    </p>
</fieldset>

}

私が抱えている問題は、ポストをデバッグしてコントローラーに戻すと、ラジオ ボタンの値が null になることです。ビューでコントロールに正しく名前を付けたと思うので、少し混乱しています。誰かがコントローラーに正しくポストされた値を取得するのを手伝ってくれますか? 前もって感謝します。

4

1 に答える 1

1

を使用するRadioButtonForと、フォームの名前が正しく関連付けられます。

@Html.RadioButtonFor(model => model.Weight, "true")
@Html.RadioButtonFor(model => model.Quantity, "true")

(plain を使用する場合RadioButton、最初のパラメーターは のようなプロパティ名にする必要があります@Html.RadioButton("Weight", "true")。ただし、入れ子になったクラスや部分ビューなどの場合はより複雑になるため、上記のように厳密に型指定された形式を使用することをお勧めします。)


編集 ラジオボタンは同じグループにある必要があるため、ビューモデルを微調整する必要があります。

@Html.RadioButtonFor(model => model.UnitType, "Weight")
@Html.RadioButton(model => model.UnitType, "Quantity")

したがって、モデルにはUnitTypeプロパティが必要ですが、それでも と を使用する必要がある場合はWeightQuantity更新するように設定できます。

private string _unitType;

public string UnitType 
{
    get { return _unitType; }
    set
    {
        _unitType = value;
        Weight = (_unitType ?? "").Equals("Weight", StringComparison.CurrentCultureIgnoreCase);
        Quantity = (_unitType ?? "").Equals("Quantity", StringComparison.CurrentCultureIgnoreCase);
    }
}
于 2012-09-15T03:58:32.933 に答える