1

mvc4 アプリケーションでチェックボックスの状態を維持するのに本当に問題があります。新しい値でモデルをビューに戻す前に、その値をコントローラー ロジックに送信し、指定された値に基づいてモデルのリストを更新しようとしています。私のチェックボックスが「リストに無効な要素を表示する」タイプの機能であることを考えると、オンとオフを切り替えることができる必要があります。私はこれに対して非常に多くの異なる解決策を見てきましたが、それらを機能させることができないようです:(

ここに私の見解の一部があります:

@model MyProject.Models.HomeViewModel

<div class="row-fluid">
    <div class="span12">
        <div class="k-block">
            <form action="~/Home/Index" name="refreshForm" method="POST">
                <p>Include disabled units: @Html.CheckBoxFor(m => m.Refresh)</p>
                <input type="submit" class="k-button" value="Refresh" />
           @* KendoUI Grid code *@
        </div>
    </div>

ホームビューモデル:

public class HomeViewModel
{
    public List<UnitService.UnitType> UnitTypes { get; set; }
    public bool Refresh { get; set; }
}

HomeViewController にはリファクタリングが必要ですが、それは新しいタスクになります。

[HttpPost]
public ActionResult Index(FormCollection formCollection, HomeViewModel model)
{
    bool showDisabled = model.Refresh;

    FilteredList = new List<UnitType>();
    Model = new HomeViewModel();
    var client = new UnitServiceClient();
    var listOfUnitsFromService = client.GetListOfUnits(showDisabled);

    if (!showDisabled)
    {
        FilteredList = listOfUnitsFromService.Where(unit => !unit.Disabled).ToList();
        Model.UnitTypes = FilteredList;

        return View(Model);
    }

    FilteredList = listOfUnitsFromService.ToList();
    Model.UnitTypes = FilteredList;

    return View(Model);
}
4

1 に答える 1

1

Modelビューに戻すと、Modelプロパティが入力されますが、チェックボックスの値はモデルの一部ではありません! 解決策は、をFormCollection完全に廃止し、ビュー モデルにチェックボックスを追加することです。

public class HomeViewModel
{
    ... // HomeViewModel's current properties go here
    public bool Refresh { get; set; }
}

あなたの見解では:

@Html.CheckBoxFor(m => m.Refresh)

コントローラーで:

[HttpPost]
public ActionResult Index(HomeViewModel model)
{
    /* Some logic here about model.Refresh */
    return View(model);
}

余談ですが、現在のようにこの値をセッションに追加する理由はわかりません (投稿したコードに明らかでないものがない限り.

于 2013-04-26T07:05:20.670 に答える