【问题标题】:Save checkbox list value Sql database in MVC5在MVC5中保存复选框列表值Sql数据库
【发布时间】:2019-10-15 06:31:37
【问题描述】:

我想将字段和复选框存储在表单中的数据库表中:连接表包含以下字段:

连接表:

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>();

现在如何保存帖子中的信息并将其保存到注册表中。 ??????对寄存器中的更新、删除操作应该进行哪些修改?

寄存器控制器:

[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);
}

【问题讨论】:

  • 您的控制器和数据库功能在哪里?您只是创建域模型,但这里没有数据访问代码!
  • 还向我们展示了您在绑定和尝试保存方面所做的工作

标签: c# asp.net asp.net-mvc-5


【解决方案1】:

您应该阅读有关 MVC 模型绑定的信息。通常它可以毫无问题地绑定它。但列表略有不同。您要提供列表中项目的索引。这就是为什么最好使用 for 而不是 foreach

检查这个视图并抓取它的 POSTed 值来检查。请注意,所有列表项都使用其在列表中的索引显示。

<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>

【讨论】:

  • 从checkboxes中选择值时,我应该如何检查信息是否记录在控制器的表寄存器中??????
  • 应该对控制器进行哪些更改以保存复选框值???
  • 换句话说,应该进行哪些更改才能将选定的值保存到表寄存器中???感谢您的指导
  • 您将属性 IsSelected 设置为 true。只需创建控制器方法,称为 Bind 并调试哪些信息可用
猜你喜欢
  • 2020-03-15
  • 2015-06-19
  • 2017-06-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-01-29
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多