Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
154 views
in Technique[技术] by (71.8m points)

c# - Pass List of Checkboxes into View and Pull out IEnumerable


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You cannot bind to a collection using a foreach loop. Nor should you be manually generating your html, which in this case would not work because unchecked checkboxes do not post back. Always use the strongly typed html helpers so you get correct 2-way model binding.

You have not indicated what you models are, but assuming you have a User and want to select Roles for that user, then create view models to represent what you want to display in the view

public class RoleVM
{
  public int ID { get; set; }
  public string Name { get; set; }
  public bool IsSelected { get; set; }
}
public class UserVM
{
  public UserVM()
  {
    Roles = new List<RoleVM>();
  }
  public int ID { get; set; }
  public string Name { get; set; }
  public List<RoleVM> Roles { get; set; }
}

In the GET method

public ActionResult Edit(int ID)
{
  UserVM model = new UserVM();
  // Get you User based on the ID and map properties to the view model
  // including populating the Roles and setting their IsSelect property
  // based on existing roles
  return View(model);
}

View

@model UserVM
@using(Html.BeginForm())
{
  @Html.HiddenFor(m => m.ID)
  @Html.DisplayFor(m => m.Name)
  for(int i = 0; i < Model.Roles.Count; i++)
  {
    @Html.HiddenFor(m => m.Roles[i].ID)
    @Html.CheckBoxFor(m => m.Roles[i].IsSelected)
    @Html.LabelFor(m => m.Roles[i].IsSelected, Model.Roles[i].Name)
  }
  <input type"submit" />
}

Then in the post method, your model will be bound and you can check which roles have been selected

[HttpPost]
public ActionResult Edit(UserVM model)
{
  // Loop through model.Roles and check the IsSelected property
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...