【发布时间】:2012-08-22 16:23:42
【问题描述】:
所以,我创建了一个包含两个列表框的视图,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 列表框。我还编写了一些 JavaScript,让用户可以将项目(包括 id 和 label)从 AvailableServices ListBox 移动到 SelectedServices强>列表框。那里也没有问题。
现在这是我的问题...我已经阅读了各种帖子,但我仍然不明白如何在表单提交时最好地将数据从我的 SelectedServices ListBox 传递回我的控制器,因为我需要为每个选择同时捕获 id 和 label。
我的目标是在 SPServiceType 表中为 SelectedServices 列表框中的每个项目创建一个新的数据库行,但我一无所知。现在我用于保存数据的控制器如下所示:
[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 和 label 值。
任何关于如何在视图中处理此问题的代码示例,或控制器中的发布操作,或一般方法建议,将不胜感激。
【问题讨论】:
标签: c# javascript asp.net asp.net-mvc-3