简体   繁体   中英

Save checkbox list value Sql database in MVC5

I want to store fields and checkboxes in a database table in a form: The connection table contains the following fields:

connection table:

public  partial class Connection
{
    [Key]
    public int ID { get; set; }
    public string CommunicationName { get; set; }
    public bool IsSelected { get; set; }
}

Register table:

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

The values of the checkbox fields in the list are displayed using the following method:

questionForm.Communications = db.Connections.ToList<Connection>();

Now how to save the information in the post and save it to the register table. ????????? What changes should be Create to the update, delete operation in the register?

controller for register:

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

You should read about MVC model binding. Normally it could bound it without any problem. But lists are slightly different. You are to provide index of item in list. That is why it is better to use for , instead of foreach .

Check this view and grab it POSTed values to examine. Pay attention, that all list items are displayed using its index in list.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM