0

I'm trying to initialize my checkbox in controller like the code below, but in the view it's not selected whether it's true or false

controller :

 foreach (var item in AssignedUsers)
 {
     if (dc.App_UserTasks.Any(u => u.UserId == item.UserId && u.TaskId == ProjectTask.Id))
        {
            Users.Single(u => u.Id == item.Id).IsChecked = true;
        }
     else
        {
             Users.Single(u => u.Id == item.Id).IsChecked = false;
        }
  }

view:

 @for (int i = 0; i < Model.Responsibles.Count; i++)
    {
         @Html.CheckBoxFor(u => u.Responsibles[i].IsChecked)            
    }

send model from controller to view :

 var EPT = new EditProjectTaskModel
            {
                ProjectId = ProjectTask.ProjectId,
                Title = ProjectTask.Title,
                ProjectName = ProjectTask.App_Project.ProjectName,
                Id = ProjectTask.Id,
                Description = ProjectTask.Description,
                EstimatedTime = ProjectTask.EstimatedTime,
                Status = ProjectTask.Status,
                Responsibles = Users.ToList()
            };
            return PartialView("_EditProjectTask", EPT);
0

1 Answer 1

1

Assuming your User ViewModel looks like this

public class UserViewModel 
{
  public string Name { set;get;}
  public int UserId { set;get;}
  public bool IsSelected { set;get;}
}

And you have your main view model has a collection of this UserViewModel

public class EditProjectTaskModel 
{
  public List<UserViewModel > Responsibles { set; get; }

  public EditProjectTaskModel()
  {
    if(this.Responsibles ==null)
       this.Responsibles =new List<UserViewModel >();
  }
}

Create an editor template called Responsibles.cshtml with the below content

@model YourNameSpace.UserViewModel 
@Html.CheckBoxFor(x => x.IsSelected)
@Html.LabelFor(x => x.IsSelected, Model.Name)
@Html.HiddenFor(x => x.UserId)

Now include that in your main view like this, instead of the loop

@model EditProjectTaskModel
@using (Html.BeginForm())
{
  //other elements
 @Html.EditorFor(m=>m.Responsibles)
 <input type="submit" value="Save" />
}

If you want to get the selected checkboxes on a form submit.

[HttpPost]
public ActionResult Save(EditProjectTaskModel model)
{
  List<int> userIDs=new List<int>();
   foreach (UserViewModel user in model.Responsibles)
   {
     if (user.IsSelected)
     {
       //you can get the selected user id's here
       userIDs.Add(user.UserId);    
     }
   } 
}
Sign up to request clarification or add additional context in comments.

2 Comments

foreach (UserViewModel user in model.Responsibles)
@3nigma : Thanks 3nigma. Fixed that.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.