ASP.NET MVC-如何捕获多个复杂的ListBox值并将其保存到数据库中

ASP.NET MVC - how to capture and save multiple complex ListBox values to database

本文关键字:保存 数据库 ListBox MVC- NET 何捕获 复杂 ASP      更新时间:2023-09-26

因此,我创建了一个包含两个ListBox的视图,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列表框移动到SelectedServices

现在我的问题是。。。我读了很多文章,但我仍然不知道如何在表单提交时将数据从SelectedServicesListBox最好地传递回我的控制器,因为我需要为每个选择捕获id标签

我的目标是在SPServiceType表中为SelectedServicesListBox中的每个项创建一个新的数据库行,但我对此一无所知。现在我保存数据的控制器看起来是这样的:

[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值传递到隐藏列表<>以便我的模型绑定更容易完成?

重申一下,我想捕获选择的id标签值。

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

我也有类似的问题。

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