0

我正在尝试像下面的代码一样在控制器中初始化我的复选框,但是在视图中它没有被选中是真还是假

控制器 :

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

看法:

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

将模型从控制器发送到视图:

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

1 回答 1

1

假设您的用户 ViewModel 看起来像这样

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

你有你的主视图模型有这个 UserViewModel 的集合

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

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

创建一个Responsibles.cshtml使用以下内容调用的编辑器模板

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

现在像这样在你的主视图中包含它,而不是循环

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

如果您想在表单提交上获得选中的复选框。

[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);    
     }
   } 
}
于 2012-05-21T19:00:50.167 回答