Your question is two broad to answer. So i will give you a generic example which you need to customize according to your scenario.
Assuming your view is to assign some tasks to users. Each user can be assigned to one ore more tasks.
So i will create a viewmodel like this.
public class UserViewModel
{
public int UserId { set;get;}
public string Name { set;get;}
public List<Task> Tasks { set;get;}
public UserViewModel()
{
Tasks=new List<UserTask>();
}
}
public class UserTask
{
public int ID { set;get;}
public string Name { set;get;}
public bool IsSelected { set;get;}
}
Now in your GET
action, you create an object of UserViewModel and set the Tasks property to a list of available taks (from your database may be)
public ActionResult Add()
{
var vm=new UserViewModel();
vm.Tasks=GetAvailableTasks();
return View(vm);
}
Assuming GetAvailableTasks
is a method which returns a list of UserTask
objects.
Now create an editor templates. Go to your ~/Views/YourControllerName
folder and create a folder called EditorTemplates
. Add a new view to the newly created folder and give name as Task.cshtml
. Add the below code to that
@model YourNameSpace.UserTask
<p>
@Html.CheckBoxFor(x => x.IsSelected) Model.Name
@Html.HiddenFor(x => x.ID)
</p>
Now go back to your main view and use EditorFor
helper method to bring the EditorTemplate.
@model YourNamespace.UserViewModel
<h2>Quiz 24</h2>
@using (Html.BeginForm())
{
@Html.EditorFor(x=>x.Tasks)
<input type="submit" />
}
Now when the form gets submitted, you can get the selected checkbox values like this
[HttpPost]
public ActionResult Save(UserViewModel model)
{
List<int> taskIds=new List<int>();
foreach (var task in model.Tasks)
{
if (task.IsSelected)
{
//you can get the selected task id's here.
taskIds.Add(task.ID);
}
}
//to do : save and redirect (PRG pattern)
}
Here is a blog post explaining how to use EditorTemplates to handle collections on form submit. the post is showing an example to handle radio buttons.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…