[英]Save checkbox list value Sql database in MVC5
我想以表單的形式將字段和復選框存儲在數據庫表中:連接表包含以下字段:
連接表:
public partial class Connection
{
[Key]
public int ID { get; set; }
public string CommunicationName { get; set; }
public bool IsSelected { get; set; }
}
注冊表:
public class RegisterForm
{
#region Ctor
public RegisterForm()
{
}
#endregion Ctor
#region Properties
[Key]
[Required]
public int ID { get; set; }
[Required(ErrorMessage = ("Required"))]
[StringLength(50, ErrorMessage = "This field must be a maximum of 50 characters")]
[TypeConverter("NVarchar(121)")]
[DisplayName("FullName")]
public string FullName { get; set; }
public string Email { get; set; }
public List<Connection> Communications { get; set; }
}
列表中復選框字段的值使用以下方法顯示:
questionForm.Communications = db.Connections.ToList<Connection>();
現在如何保存帖子中的信息並將其保存到注冊表中。 ?????? 對寄存器中的更新、刪除操作應該進行哪些更改?
controller 用於寄存器:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "ID,FullName,PhoneNumber,Email,Communication,")]RegisterForm questionForm)
{
if (ModelState.IsValid)
{
db.Registers.Add(questionForm);
var data = db.SaveChanges();
return View("FormSuccessfullySubmitted");
}
return View(questionForm);
}
您應該閱讀有關 MVC model 綁定的信息。 通常它可以毫無問題地綁定它。 但列表略有不同。 您要提供列表中項目的索引。 這就是為什么最好使用for而不是foreach 。
檢查這個視圖並抓住它發布的值來檢查。 請注意,所有列表項都使用其在列表中的索引顯示。
<table class="table">
@using (Html.BeginForm("Bind", "Bind", FormMethod.Post))
{
for (int i = 0; i < Model.Count(); i++)
{
<tr>
<td>
@Html.DisplayFor(modelItem => Model[i].CommunicationName)
</td>
<td>
@Html.CheckBoxFor(modelItem => Model[i].IsSelected)
</td>
</tr>
}
<button type="submit">Submit</button>
}
</table>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.