![](/img/trans.png)
[英]ASP.NET MVC Multiselect ListBox is not selecting multiple values
[英]ASP.NET MVC - how to capture and save multiple complex ListBox values to database
因此,我创建了一个包含两个ListBoxes的View: AvailableServices和SelectedServices :
@Html.ListBoxFor(x => x.AvailableServices, Enumerable.Empty<SelectListItem>(), new { id = "serviceID" })
@Html.ValidationMessageFor(model => model.AvailableServices)
@Html.ListBoxFor(x => x.SelectedServices, Enumerable.Empty<SelectListItem>(), new { id = "selectedserviceID" })
@Html.ValidationMessageFor(model => model.SelectedServices)
供参考,这是我的ViewModel:
namespace Services.ViewModels
{
public class SPServiceTypeViewModel
{
public int Id { get; set; }
public int SPCompanyAccountID { get; set; }
[Display(Name = "Service Category")]
public IEnumerable<SelectListItem> ServiceCategory { get; set; }
[Display(Name = "Available Services")]
public IEnumerable<SelectListItem> AvailableServices { get; set; }
[Display(Name = "Your Services")]
public IEnumerable<SelectListItem> SelectedServices { get; set; }
}
}
我的控制器会毫无问题地填充AvailableServices ListBox。 我编写了一些JavaScript,使用户可以将项目(包括id和label )从AvailableServices ListBox移到SelectedServices列表框。 那里也没问题。
现在这是我的问题...我已经阅读了许多文章,但是我仍然不明白如何在表单提交后最好地将数据从SelectedServices ListBox传递回我的控制器,因为我需要同时捕获ID和标签每个选择。
我的目标是在SPServiceType表中为SelectedServices ListBox中的每个项目创建一个新的数据库行,我一无所知。 现在,我用于保存数据的控制器如下所示:
[HttpPost]
public ActionResult Create(SPServiceTypeViewModel viewModel)
{
foreach (var item in viewModel.SelectedServices)
{
var spServiceType = new SPServiceType
{
SPCompanyAccountId = viewModel.SPCompanyAccountID,
ServiceCategory = ???,
};
db.SPServiceType.Add(spServiceType);
db.SaveChanges();
return RedirectToAction("Create", "SPServiceLocation");
}
我是否不需要在ViewModel中使用IENumerable? 我是否需要使用JavaScript在提交之前将我的SelectedServices值传递给隐藏的List <>,以便更轻松地完成模型绑定?
重申一下,我想捕获选择的ID和标签值。
任何有关如何在“视图”中实现此功能的代码示例,或在Controller中执行Post操作,或获得常规的方法建议,将不胜感激。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.