超级简单的实现多选列表框的编辑视图 [英] Super simple implementation of multiselect list box in Edit view

查看:149
本文介绍了超级简单的实现多选列表框的编辑视图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Using MVC4 here with EF and CF (badly)

我有这样一个类:

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.Features收集pre-选择这些功能。

On the Edit view for the Device model I would like for there to be a ListBox that contains all elements of the Feature model (Desc property displayed) with those features contained in the device.Features collection pre-selected.

然后,当用户点击保存在编辑来看,所选项目的ListBox中当前集合被写回设备的功能集合。

Then, when the user clicks Save on the Edit view, the current collection of selected items in the ListBox gets written back to the device's Features collection.

这是什么控制器code和CSHTML看起来像这一招?

What does the controller code and cshtml look like for this trick?

感谢您的时间,
戴夫

Thank you for your time, Dave

推荐答案

与往常一样,你可以通过编写一个会满足你所描述的视图要求的视图模型启动:

As always you could start by writing a view model that will meet the requirements of the view you described:

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

,然后你的控制器:

and then your controller:

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

这篇关于超级简单的实现多选列表框的编辑视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆