1

I am rendering my form using razor. I iterate over class .control_group that's inside a form and create objects that I need to send back to controller. My form has checkboxes and hidden input values. Problem I am facing now is this. Checkbox elements rendered by razor have two inputs, one is hidden and other one is shown. When I collect form data I am always getting last input value (hidden one, and it's always false) How can I get the true value?

enter image description here

Current data sent to controller (everything is false):

{"ajaxData":[{"Id":"1","RoleId":"1","R":"false","W":"false","E":"false","D":"false"},{"Id":"2","RoleId":"2","R":"false","W":"false","E":"false","D":"false"}]}

Collecting data like this (found similar problem here on SO):

var ajaxData = $('.control_group').map(function (i, group) {
     var data = {};
     $(group).find(':input').each(function () {
          data[this.name] = this.value;
      });
      return data;
}).get();

ajaxData = JSON.stringify({ 'ajaxData': ajaxData });

console.log(ajaxData);

Controller looks like this:

    public void SendData(List<SomeClass> ajaxData)
    {
        var data = ajaxData;
    }

    public class SomeClass
    {
        public int Id { get; set; }
        public int RoleId { get; set; }
        public bool R { get; set; }
        public bool W { get; set; }
        public bool E { get; set; }
        public bool D { get; set; }
    }
BenG
  • 14,826
  • 5
  • 45
  • 60
azza idz
  • 623
  • 3
  • 13
  • 27
  • When is the code described as "Collecting data" called? – user449689 Nov 24 '15 at 15:22
  • Is there any reason why you are not just serializing the form? - `$.post(url, $('form').serialize(), ....` –  Nov 24 '15 at 20:11
  • Although I have just noticed your view is wrong (invalid html) if this is for a collection. You need to generate your form controls using a `for` loop or `EditorTemplate` –  Nov 24 '15 at 20:31

2 Answers2

0

It is by design, you can read about this here: asp.net mvc: why is Html.CheckBox generating an additional hidden input

I can suggest you while iterating the elements do the following

if the form has another element with the same name, and it is not check box, skip it.

this way you can just collect the correct fields.

I am most certainly sure that you can handle this with JQUERY, if not, post a JSFIDDLE so we can help you.

Community
  • 1
  • 1
Avi Fatal
  • 1,550
  • 8
  • 8
0

Razor syntax always creates a hidden field for radio button & checkbox. You can change your :input selector to :input:checkbox to do your task.

var ajaxData = $('.control_group').map(function (i, group) {
 var data = {};
 $(group).find(':input:checkbox').each(function () {
      data[this.name] = this.value;
  });
  return data;
}).get();

ajaxData = JSON.stringify({ 'ajaxData': ajaxData });

console.log(ajaxData);
Ibrahim Khan
  • 20,616
  • 7
  • 42
  • 55