How to know the selected checkboxes from within the HttpPost Create action method?
You can use Editor Templates to do this.
First, create a new class for the course selection and update your view model to have a collection of that class.
public class SelectedCourse
{
public int Id { get; set; }
public string Name { get; set; }
public bool IsSelected { get; set; }
}
public class StudentCourseVM
{
public int StudentId { set; get; }
public IEnumerable<SelectedCourse> SelectedCourses { get; set; }
}
You do not need to copy and paste all the properties from your entity model to your view model. View model needs only those properties which the view absolutely need. I am assuming you want to assign courses to a specific student
Now go to your ~/Views/YourControllerName
and create a directory called EditorTemplates. Create a new razor file there and give the name SelectedCource.cshtml
Paste this code to the new file
@model SelectedCourse
<label>@Model.Name</label>
<input asp-for="IsSelected"/>
<input type="hidden" asp-for="Id" />
Now in your GET action, create an object of the view model, load the SelectedCourses collection and send it to the view.
public IActionResult Create()
{
// I hard coded the student id and the courses here.
// you may replace it with real data.
var vm = new StudentCourseVM { StudentId = 12 };
//Assuming we are assigning courses to the student with id 12
vm.SelectedCourses = new List<SelectedCourse>()
{
new SelectedCourse {Id = 1, Name = "CSS"},
new SelectedCourse {Id = 2, Name = "Swift"},
new SelectedCourse {Id = 3, Name = "IOS"},
new SelectedCourse {Id = 4, Name = "Java"}
};
return View(vm);
}
Now in your main view(Create.cshtml
) which is strongly typed to StudentCourseVM,Use EditorFor
helper method on the SelectedCourses
property.
@model StudentCourseVM
<form asp-action="Create">
@Html.EditorFor(f=>f.SelectedCourses)
<input type="hidden" asp-for="StudentId"/>
<input type="submit"/>
</form>
The Editor template will execute code in the editor template file for each item in the SelectedCourses collection. So you will have the course name and a checkbox visible to the user.
In your HttpPost action method, you can use the same view model as the parameter. When the form is submitted, you may loop through the items in SelectedCourses
property check the IsSelected
property value. The courses user selected in the ui will have a true
value.
[HttpPost]
public IActionResult Create(StudentCourseVM model)
{
var studentId = model.StudentId;
foreach (var modelSelectedCourse in model.SelectedCourses)
{
if (modelSelectedCourse.IsSelected)
{
//this one is selected. Save to db
}
}
// to do : Return something
}
Pre-selecting some checkboxes on page load
Sometimes you want to pre select some checkboxes when the page loads (Ex : For your edit screen you want to show already saved courses as checked). To do this, you simply need to set the IsSelected
property of the corresponding SelectedCourse
object to true in your GET action method.
public IActionResult Edit(int id)
{
// I hard coded the student id and the courses here.
// you may replace it with real data.
var vm = new StudentCourseVM { StudentId = id };
//Assuming we are assigning courses to the student with id 12
vm.SelectedCourses = new List<SelectedCourse>()
{
new SelectedCourse {Id = 1, Name = "CSS"},
new SelectedCourse {Id = 2, Name = "Swift", IsSelected = true },
new SelectedCourse {Id = 3, Name = "IOS", IsSelected = true },
new SelectedCourse {Id = 4, Name = "Java"}
};
return View(vm);
}
The above code will pre select the checkboxes for Swift and IOS.
How to get the selected checkbox value in post action in mvc 2
Its very simple . Use FormCollection in your Parameter list of Action method in your controller and then create a String Array for your CheckBoxBox values in your model .
Now Assign formvalue["Your_CheckBoxBox_value"].Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
to your newly created String Array in your Controller ........
public ActionResult Create()
{
ITrackdayRepository trackdayResp = new TrackdayRepository();
IQueryable<Object> getAllEvents = trackdayResp.GetEventsSelectlist();
var m = new SelectList(getAllEvents,"ID","Name");
ViewData["events"] = new SelectList(getAllEvents.ToList(), "EventID","Date");
return View();
}
//
// POST: /Admin/Voucher/Create
[HttpPost]
public ActionResult Create(FormCollection collection)
{
try
{
// Get all the selected checkboxlist, do db insertion
model.CheckBoxValues=collection["Your_CheckBox_valueOnView"].Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
return RedirectToAction("Index");
}
catch
{
return View();
}
}
Selected Checkboxes are not showing up in the HttpPost action method in asp.net core mvc 3.1
Try to use code below:
@model IList<Practice.MVC.Models.Category>
@{
ViewBag.Title = "Get Selected CheckBoxes";
}
<h1>@ViewBag.Title</h1>
<form asp-controller="Test" asp-action="GetSelectedCheckBoxes" method="post">
@*@foreach (var category in Model)*@
@for(int i=0; i < Model.Count; i++)
{
@Html.CheckBox("categories[" + i + "].CheckboxAnswer", Model[i].CheckboxAnswer)
<label asp-for="@Model[i].CategoryId">@Model[i].CategoryName</label>
@Html.Hidden("categories[" + i + "].CategoryId", Model[i].CategoryId)
@Html.Hidden("categories[" + i + "].CategoryName", Model[i].CategoryName)
}
<input type="submit" id="Submit" name="Submit" value="Submit" />
</form>
To be the MVC binding work properly it's necessary to use indexing for the collection items.
Therefore, to make code shorter in the fragment above the IEnumerable
is replaced by the IList
and the for
is used instead of the foreach
.
In additional, the <input>
tag helper generates the id
and name
HTML attributes for the expression name specified in the asp-for
attribute. But in this case the index will not included to the 'id' and the name
. See The Input Tag Helper
This is why the HTML Helper alternatives to Input Tag Helper is used.
Posting selected checkboxes to controller action with viewModel
I'll try to answer it the best way I understand. So, assuming you have created the 'table' with the checkboxes in them which I suppose looks something like this:
<form>
<table>
<tr><td><input type='checkbox' value='1' name='myCheckbox' />Some text</td></tr>
<tr><td><input type='checkbox' value='2' name='myCheckbox' />Some text</td></tr>
<tr><td><input type='checkbox' value='3' name='myCheckbox' />Some text</td></tr>
<tr><td><input type='checkbox' value='4' name='myCheckbox' />Some text</td></tr>
</table>
<input type="submit" />
</form>
Inside your ProductModel Class:
public class ProductModel
{
// Define the property here.
public int[] MyCheckbox { get; set; }
// The constructor where you do the initialization
public void ProductModel(int[] myCheckbox)
{
MyCheckbox = myCheckbox;
}
}
In your controller method:
[HttpPost]
public ActionResult SomeMethod(ProductModel productModel)
{
foreach(int value in productModel.MyCheckbox)
{
// Your code here..
}
}
You'll get the value of checkboxes as an array in your controller method.
How do I get the selected values of a checkbox list?
In the simplest case, the controller action should look like this (in the Product controller):
[HttpPost]
public ActionResult Save(string[] Categories)
{
// Process selected checkbox values here, using the Categories array
...
}
In a more complex case (with more form fields), it may be better to use a view model, and add a Categories property to it.
public class MyViewModel
{
...
public string[] Categories { get; set; }
...
}
Controller action:
[HttpPost]
public ActionResult Save(MyViewModel model)
{
// Process selected checkbox values here, using the model.Categories array
...
}
Simple Q & A, but hopefully it will help someone looking for the answer (like I was, when I first started learning ASP.NET MVC).
P.S. If you've got something better or more detailed, please post it.
How to get list of checked boxes in controller
Your MVC controller should take FormCollection:
HttpPost, ValidateAntiForgeryToken]
public ActionResult Failid(FormCollection nv)
If nothing still comes back, verify the name is being rendered with your expectation. Also, I don't remember completely but do you have to set your own value with checkbox? In order to post something, a value must be specified, and this value is what gets sent back to the server, and then converted to a boolean by MVC.
Performing HttpPost to store CheckBox Selected Values in Database
Your model is null because you are not passing anything from Controller ACtion. Your CheckView ActionMethod should be an action that generates the view. Then your "CheckView" button should call another HttpPost action that would look like your previous CheckView. Let me know if it helps in the comments.
Action Result method that for the View:
public ActionResult CheckView(ProductModel model)
{
return View("CheckView", model);
}
Action for button click.
[HttpPost]
public ActionResult TestView(FormCollection collection)
{
try
{
ProductModel model = new ProductModel();
// Get all the selected checkboxlist, do db insertion
model.CheckedColumn = collection["CheckView"].Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
return RedirectToAction("Index");
}
catch
{
return View();
}
}
And in View something like this:
@using (@Html.BeginForm("TestView", "Controller Name"))
{
//all your input here
// submit button here
}
Pass values of checkBox to controller action in asp.net mvc4
If a checkbox is checked, then the postback values will contain a key-value pair of the form [InputName]=[InputValue]
If a checkbox is not checked, then the posted form contains no reference to the checkbox at all.
Knowing this, the following will work:
In the markup code:
<input id="responsable" name="checkResp" value="true" type="checkbox" />
And your action method signature:
public ActionResult Index(string responsables, bool checkResp = false)
{
//Do Something
}
This will work because when the checkbox is checked, the postback will contain checkResp=true
, and if the checkbox is not checked the parameter will default to false.
Related Topics
Are Empty Interfaces Code Smell
Prevent C# App from Process Kill
ASP.NET Dynamically Button with Event Handler
Get All Associate/Composite Objects Inside an Object (In Abstract Way)
Why Can't I Use Interface with Explicit Operator
Using C# to Search a CSV File and Pull the Value in the Column Next to It
Is There a Port of Memcache to .Net
How to Partially Project a Child Object with Many Fields in Nhibernate
Error Message "Cs5001 Program Does Not Contain a Static 'Main' Method Suitable for an Entry Point"
Automatic Cookie Handling C#/.Net Httpwebrequest+Httpwebresponse
Only Primitive Types or Enumeration Types Are Supported in This Context
How to Bind to a Dynamicresource So You Can Use a Converter or Stringformat, etc.? (Revision 4)
JSONconvert.Deserializer Indexing Issues
Initializing an Array of Structs in C#
Convert Datatable to Ienumerable<T>
How to Convert a System.Io.Stream to a Windows.Storage.Streams.Irandomaccessstream