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> } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
相关内容
- asp.net-mvc – Action方法中的routeValues不接受ExpandoOb
- asp.net – 处理程序“PageHandlerFactory-ISAPI-4.0_32bit
- asp.net-mvc – 我应该使用AsyncController在ASP.NET MVC 4
- asp.net-mvc-3 – asp.net mvc3请求线程亲和
- asp.net-mvc – 添加一个默认的SelectListItem
- ASP.NET“死亡黄屏”如何显示代码?
- asp.net-mvc – 阻止bingbot抓取我的网站
- asp.net-mvc – MVC WebApi不使用AutofacWebApiDependencyR
- ASP.NET会员密码重置
- IE不保存asp.net身份验证令牌/ cookie
推荐文章
站长推荐
热点阅读