c# - 如何将用户复选框检查写入数据库中的多条记录 - 使用 MVC、C#、Razor、nHibernate

标签 c# asp.net-mvc razor nhibernate

所以我试图将用户选中的复选框的值插入到我的数据库中。

在我的 ViewModel 中:

    [Display(Name = "Title")]
    public string Title { get; set; }
    public IEnumerable<SelectListItem> UserTitlelist { get; set; }
    public IEnumerable<SelectListItem> Titles { get; set; }

在我看来:

 @foreach (var item in Model.Titles)
  {
    <label class="managelabel" style="padding: 0 5px 0 5px;"><input name="Title" type="checkbox" value="@item.Value" @checkedcheckbox> @item.Text</label>
  }

在我的 Controller 中:

 var titleToInsert = new UserTitle
  {
   UserId = currentUserId,
   TitleId = model.Title[];
   };
  UserManagerService.UpdateUserTitles(titleToInsert);

在 UserManagerService 中:

public static int UpdateUserTitles(UserTitle userTitle)
    {

        using (ITransaction transaction = Context.BeginTransaction())
        {
            foreach (var x in userTitle)
            {
                Context.Save(userTitle);
            }
            transaction.Commit();
        }
        return 0;
    }

最佳答案

您的 View 模型不正确,与您正在编辑的内容完全没有关系。 SelectListItem 是用于 @Html.DropDownListFor() 的类,而不是用于复选框的集合。

你的 View 模型应该是

public class TitleVM
{
  public int ID { get; set; }
  public string Name { get; set; }
  public bool IsSelected { get; set; }
}

public class UserTitleVM
{
  .... // other properties
  public List<TitleVM> Titles { get; set; }
}

在 View 中

@model UserTitleVM
@using (Html.BeginForm())
{
  ....
  for(int i = 0; i < Model.Titles.Count; i++)
  {
    @Html.HiddenFor(m => m.Titles[i].ID)
    @Html.CheckBoxFor(m =>m.Titles[i].IsSelected)
    @Html.LabelFor(m => m.Titles[i].IsSelected, Model.Titles[i].Name)
  }

在 Controller 中

public ActionResult Edit(UserTitleVM model)
{
  // Get the ID's of the selected titles
  List<int> selectedTitles = model.Titles.Where(t => t.IsSelected).Select(t => t.ID);
  ....

关于c# - 如何将用户复选框检查写入数据库中的多条记录 - 使用 MVC、C#、Razor、nHibernate,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32725510/

相关文章:

c# - 具有偏移量的 GroupBy DateTime 列 C# Linq

c# - 在 C# 中将字符串转换为控件名称

c# - 如何在现有 MVC 3 项目中添加/集成 SqlMembershipProvider?

c# - Razor 和 ASPX 有什么区别?

c# - 授权角色 WebAPI oauth owin

c# - 根级别的数据无效。第 1 行,位置 1。读取 xml 时

jquery - 需要有关 ASP.NET MVC 中多选项卡表单的建议

Azure Windows Server 2016 上的 ASP.NET5 CLR 网站正在运行,但在浏览器中出现 404 NOT FOUND

c# - 使用 MVC Razor View 在表中插入多行

c# - 包含特定字符的 ActionLink 路由值