【问题标题】:ASP.NET MVC - how to capture and save multiple complex ListBox values to databaseASP.NET MVC - 如何捕获多个复杂的 ListBox 值并将其保存到数据库
【发布时间】:2012-08-22 16:23:42
【问题描述】:

所以,我创建了一个包含两个列表框的视图,AvailableServicesSelectedServices

                @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,让用户可以将项目(包括 idlabel)从 AvailableServices ListBox 移动到 SelectedServices强>列表框。那里也没有问题。

现在这是我的问题...我已经阅读了各种帖子,但我仍然不明白如何在表单提交时最好地将数据从我的 SelectedServices ListBox 传递回我的控制器,因为我需要为每个选择同时捕获 idlabel

我的目标是在 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 以便我的模型绑定更容易完成?

重申一下,我想捕获选择的 idlabel 值。

任何关于如何在视图中处理此问题的代码示例,或控制器中的发布操作,或一般方法建议,将不胜感激。

【问题讨论】:

    标签: c# javascript asp.net asp.net-mvc-3


    【解决方案1】:

    我有一个similar question here

    当时的建议是接受 POST 中的选定值,并使用存储库模式(必要时进行缓存)根据需要将值转换为标签。

    【讨论】:

      猜你喜欢
      • 2011-08-23
      • 1970-01-01
      • 2017-09-05
      • 2020-12-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多