4

ここでEFとCFでMVC4を使用する(ひどい)

私はこのようなクラスを持っています:

public class Feature
{
    public int ID { get; set; }
    public string Desc { get; set; }
}

そして、このようなもの:

public class Device   //change to Devices
{
    public int ID { get; set; }
    public string Name { get; set; }
    public virtual ICollection<Feature> Features { get; set; }
}

Device モデルの Edit ビューで、Feature モデルのすべての要素 (Desc プロパティが表示されます) を含む ListBox があり、device.Features コレクションに含まれる機能が事前に選択されている必要があります。

次に、ユーザーが [編集] ビューで [保存] をクリックすると、ListBox で選択されているアイテムの現在のコレクションがデバイスの Features コレクションに書き戻されます。

このトリックのコントローラー コードと cshtml はどのようになりますか?

お時間をいただきありがとうございます、デイブ

4

1 に答える 1

17

いつものように、説明したビューの要件を満たすビュー モデルを作成することから始めることができます。

public class EditDeviceViewModel
{
    public IEnumerable<int> SelectedFeatures { get; set; }
    public IEnumerable<SelectListItem> Features { get; set; }
    public int ID { get; set; }
    public string Name { get; set; }
}

そしてあなたのコントローラー:

public class DeviceController : Controller
{
    public ActionResult Edit(int id)
    {
        Device device = (go get your device from your repository using the id)
        IList<Feature> features = (go get all features from your repository)

        // now build the view model
        var model = new EditDeviceViewModel();
        model.ID = device.ID;
        model.Name = device.Name;
        model.SelectedFeatures = device.Features.Select(x => x.ID);
        model.Features = features
            .Select(x => new SelectListItem
            {
                Value = x.ID.ToString(),
                Text = x.Name,
            })
            .ToList();

        // pass the view model to the view
        return View(model);
    }

    [HttpPost]
    public ActionResult Edit(EditDeviceViewModel model)
    {
        // model.SelectedFeatures will contain the selected feature IDs here
        ...
    }
}

そして最後にビュー:

@model EditDeviceViewModel

@using (Html.BeginForm())
{
    @Html.Html.HiddenFor(x => x.ID)
    <div>
        @Html.LabelFor(x => x.Name)
        @Html.EditorFor(x => x.Name)
    </div>
    <div>
        @Html.LabelFor(x => x.SelectedFeatures)
        @Html.ListBoxFor(x => x.SelectedFeatures, Model.Features)
    </div>

    <button type="submit">Edit</button>
}
于 2013-08-21T16:53:28.620 に答える