加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net-mvc-4 – 编辑视图中多选列表框的超级简单实现

发布时间:2020-12-16 07:34:25 所属栏目:asp.Net 来源:网络整理
导读:在这里使用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;
在这里使用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是什么样的?

感谢您的时间,
戴夫

解决方法

与往常一样,您可以从编写满足您所描述视图要求的视图模型开始:

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读