c# - 如何将 ASP.NET MVC 中的 HTML <select> 多个属性的更新值插入到数据库?

标签 c# html mysql asp.net asp.net-mvc

如何从 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/

相关文章:

c# - 如何从 C# 中的目录中获取文件列表

javascript - 使用 overflow-y 时拖动元素会隐藏

javascript - 移动设备中的 Bootstrap 菜单错误

php - 如何允许 php 文件仅由站点调用,而不是通过 Inspect Element 或 URL 调用

php - sql php函数中的插入查询

c# - 文本未到达控制台

C# - 将 HTML 无序列表转换为数组

c# - 这种 await/async 的用法是否正确?

php - 多种表单注册不起作用

mysql - 在 mysql 表中重新创建编码混合