Get correct checkbox value when using razor asp.net mvc

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-11 12:59:48

问题


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?

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; }
    }

回答1:


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.




回答2:


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);


来源:https://stackoverflow.com/questions/33896965/get-correct-checkbox-value-when-using-razor-asp-net-mvc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!