在编辑视图中超级简单地实现多选列表框

时间:2013-08-21 16:41:34

标签: asp.net-mvc-4 ef-code-first

在这里使用MVC4与EF和CF(严重)

我有一个这样的课程:

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视图中,我希望有一个ListBox,其中包含Feature模型的所有元素(显示的Desc属性),其中包含预先选择的device.Features集合中包含的那些功能。

然后,当用户在“编辑”视图上单击“保存”时,ListBox中所选项目的当前集合将被写回设备的“功能”集合。

这个技巧的控制器代码和cshtml是什么样的?

感谢您的时间, 戴夫

1 个答案:

答案 0 :(得分:16)

与往常一样,您可以先编写一个符合您所描述视图要求的视图模型:

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>
}