2
votes

can anyone please show me the code for posting a list on button click from view to controller in mvc3-asp. i have a list in which one of the list element is check box.at first i have to select some of the values from list then submit it to save the selected values only.

2

2 Answers

5
votes

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.

4
votes

You can actually skip all this rebuilding in the controller. Razor can rebuild the list of any object using a single form. You just need to fallback to the old for and assign a unique name, as well as include the primary key for that collection.

On postback razor will rebuild your ViewModel with the modified list without any extra work.

enter image description here

In the markup it looks something like this

enter image description here

And in the controller after posting back the model is rebuilt with the new data the user has entered, and also lazyBound to ForeignKey models!

enter image description here

Using checkboxes or radio inputs it's slightly different. The problem is that when a checkbox is not ticked, browsers do NOT submit it back, and the model will NOT rebuild. This is not a shortfall of VS but an intended implementation of HTML1 that still lives in HTML5!

If this happens the Index Out of Bounds will occur. So you have include a hidden field for checkboxes with a value of false before the Input Box (if a user checks it it will overwrite the false to true)

But if you are using a StronglyTyped model, like in my case, any check boxes evaluated to null are automatically set to false, known as the default value for a boolean as defined in the C# specification.