lokopi lokopi - 1 year ago 72
ASP.NET (C#) Question

How to set a hidden field from a Check box selection in jquery and passing it to the controller action method?

I want to set the Hidden field in jquery for selected checkboxes. A user can select multiple checkboxes. I have multiple checkboxes which I want to save as comma separated value in Database. I am doing this with help of jquery and setting it using hidden field but no luck.

<div id="chkbox">
<input type="checkbox" class="Course" name="Courses" id="CoursesScience" value="Science">Science<br>
<input type="checkbox" class="Course" name="Courses" id="CourseMath" value="Math">Math<br />
<input type="checkbox" class="Course" name="Courses" id="CourseIt" value="IT">IT<br />
<input type="checkbox" class="Course" name="Courses" id="CourseCommerce" value="Commerce">Commerce<br />
<input type="checkbox" class="Course" name="Courses" id="CourseEnglish" value="English">English
<input type="hidden" name="CoursesSelected" id="CoursesSelected" />

In jquery

var Values = [];
$('.Course').change(function () {
if (this.checked) {

This is not working as when I pop the value it pop last instance save in the array but not the one which is being deselected.

1) Also please tell me how I can access the hidden field in a controller.

2) Will this hidden field populate the property Courses in my class.

public partial class Register
public int Id { get; set; }
public string Name { get; set; }
public string Class { get; set; }
public string Courses { get; set; }
public string Gender { get; set; }

Answer Source

You should not need to use jquery or a hidden field. Instead I would use a view model. Create a new class that only contains the information you want to post from your view, e.g:

public class RegisterViewModel
    public string Name { get; set; }
    public string Class { get; set; }
    public string[] Courses { get; set; }
    public string Gender { get; set; }

I don't know what your controller action looks like, but it should now be something like:

public ActionResult Register(RegisterViewModel model)
  //Map the data posted to the form to your Register class
  var student = new Register();
  student.Name = model.Name;
  student.Class = model.Class;
  student.Gender = model.Gender;
  if (model.Courses != null)
    student.Courses = String.Join(",", model.Courses);

  //Then do whatever you need to do to save the data to the database

When you post your form, the Courses array should contain an element whose value is the id for each checkbox that has been ticked, e.g. ["CourseMath", "CourseCommerce"].

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download