所以我试图将用户选中的复选框的值插入到我的数据库中。
在我的 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/