dimanche 25 septembre 2016

How do I pass checked checkbox to the controller when dealing with a list?

I am trying to created check boxes for items in my list. Basically when a user is creating a task he will have a list of contacts(existing users he added) with check boxes. He will then check which users he wants to share the task with.

Model:

 public class UserTask
{
    [Key]
    public int UserTaskID { get; set; }

    [Required]
    public string ApplicationUserID { get; set; }

    [Required]
    [StringLength(20, ErrorMessage ="Can't exceed 20 characters")]
    [Display(Name = "Task Name")]
    public string Title { get; set; }

    [Column(TypeName = "date")]
    [DataType(DataType.Date)]
    public DateTime Date { get; set; }

    [Display(Name = "Done")]
    public bool Status { get; set; }

public virtual ICollection<TaskInvitee> TaskInvitees { get; set; } //Ignore 
}

ViewModel:

public class TaskViewModel
{
   public int UserTaskID { get; set; }

   public string ApplicationUserID { get; set; }

   public string Title { get; set; }

   public DateTime Date { get; set; }

   public bool Status { get; set; }

    public bool Selected { get; set; }
    public List<ApplicationUser> users { get; set; }
}

Controller Create: Long story short this code gets only the contacts that belong to the current users and matches them with all existing users so that I can extract their first name, last name and email details then I pass it to the ViewModel.

 public ActionResult Create()
    {
        IEnumerable<ApplicationUser> users = db.Users.ToList();

        IEnumerable<Contact> contacts = db.Contacts.ToList().Where(c => c.ApplicationUserID.Equals(User.Identity.Name));

        List<ApplicationUser> curUsers = new List<ApplicationUser>();

        foreach (var contact in contacts)
        {
            foreach (var user in users)
            {
                if (contact.ContactUserID.Equals(user.UserName))
                {
                    curUsers.Add(user);
                }
            }
        }

        TaskViewModel tvm = new TaskViewModel();
        tvm.users = curUsers;

        return View(tvm);
    }

Controller Create Post: Now assuming what I did in my create view is correct how do I pass to this controller and check which contacts have been checked?

   [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Create([Bind(Include = "UserTaskID,ApplicationUserID,Title,Date,Status")] UserTask userTask)
    {
        if (!String.IsNullOrWhiteSpace(userTask.Title))
        {
            userTask.ApplicationUserID = User.Identity.Name;
            userTask.Date = DateTime.Today;
            userTask.Status = false;
            db.UserTasks.Add(userTask);
            db.SaveChanges();

          //foreach(var item in list)
          //  {
          //      if(item.Selected)
          //      {
           //       pass to share action
          //      }
          //  }
            return RedirectToAction("Index");
        }

        return View(userTask);
    }

Create view: If what I did here at the "Invited contacts" heading is not correct then how to I go about adding check boxes to each contact when dealing with a list?

 @model MySchedule.ViewModels.TaskViewModel

  @using (Html.BeginForm())
  {
  var users = Model.users;
  @Html.AntiForgeryToken()

<div class="form-horizontal">
    <h4>Add Task</h4>
    <hr />
    @Html.ValidationSummary(true, "", new { @class = "text-danger" })

    <div class="form-group">
        @Html.LabelFor(model=> model.Title, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.Title, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.Title, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.Date, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.Date, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.Date, "", new { @class = "text-danger" })
        </div>
    </div>

 <div class="form-group">
            <h2>Invited Contacts</h2>
        <table class="table">

            @foreach (var item in users)
            {
                <tr>
                    <td>@Html.EditorFor(model => model.Selected)</td>
                    <td>@Html.DisplayFor(modelItem => item.FirstName)</td>
                    <td>@Html.DisplayFor(modelItem => item.LastName)</td>
                    <td>@Html.DisplayFor(modelItem => item.Email)</td>
               </tr>
           }
        </table>
</div>
    </div>

        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Add" class="btn btn-default" />
            </div>
        </div>
      }
   <div>
     @Html.ActionLink("Cancel", "Index")
      </div>

Any help is greatly appreciated

Aucun commentaire:

Enregistrer un commentaire