如何从 HTML 多个属性向数据库输入多个值?在这个问题中,我想在数据库表的一列(即 Pages 列)中输入 MultiSelectList 中的多个值。然后关于表单更新以显示之前选择的选项?我正在使用 ASP.NET MVC 和 MySQL 数据库。谢谢
创建.cshtml
<div class="box-body">
<form class="form-horizontal" method="post" action="CreatePage">
<table class="table table-striped">
<tr>
<td>Page</td>
<td><select class="form-control select2" multiple="multiple" style="width: 100%;" name="Page">
<option value="Home">Home</option>
<option value="About">About</option>
<option value="Profile">Profile</option>
</select>
</td>
</tr>
</table>
<div class="box-footer">
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</form>
</div>
CreateController.cs
[HttpPost]
public ActionResult CreatePage(MasterPage Page)
{
db.MasterPage.Add(Page);
db.SaveChanges();
return RedirectToAction("Index","Home");
}
public ActionResult Create()
{
return View();
}
MasterPage.cs
public partial class MasterPage
{
public string Page { get; set; }
}
最佳答案
您可以使用string[]
数组或 List<string>
,用于发送多个属性值。
有关更多详细信息,请查看此 Link
View Code
<div class="box-body">
<form class="form-horizontal" method="post" action="CreatePage">
<table class="table table-striped">
<tr>
<td>Page</td>
<td><select class="form-control select2" multiple="multiple" style="width: 100%;" name="Page">
<option value="Home">Home</option>
<option value="About">About</option>
<option value="Profile">Profile</option>
</select>
</td>
</tr>
</table>
<div class="box-footer">
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</form>
</div>
Controller Code
[HttpPost]
public ActionResult CreatePage(List<string> Page)
{
if (Page != null)
{
foreach(var item in Page)
{
db.MasterPage.Add(new MasterPage(){ Page = item});
db.SaveChanges();
}
}
return RedirectToAction("Index", "Home");
}
public ActionResult Create()
{
return View();
}
关于c# - 如何将 ASP.NET MVC 中的 HTML <select> 多个属性的更新值插入到数据库?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59025108/