Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

asp.net mvc - Submit a List from View to Controller

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.

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...