使用razor asp.net mvc时获取正确的复选框值

时间:2015-11-24 15:00:49

标签: javascript jquery json ajax asp.net-mvc

我正在使用剃刀渲染我的表格。我遍历表单中的using OpenNLP.Tools.SentenceDetect; namespace Test { internal class Program { private static readonly string currentDirectory = Environment.CurrentDirectory + "/../../"; private static void Main(string[] args) { var inputText = "C#[note 2] (pronounced as see sharp) is a multi-paradigm programming language encompassing strong typing, imperative, declarative, functional, generic, object-oriented (class-based), and component-oriented programming disciplines. It was developed by Microsoft within its .NET initiative and later approved as a standard by Ecma (ECMA-334) and ISO (ISO/IEC 23270:2006). C# is one of the programming languages designed for the Common Language Infrastructure. C# is intended to be a simple, modern, general-purpose, object-oriented programming language.[7] Its development team is led by Anders Hejlsberg. The most recent version is C# 6.0, which was released on July 20, 2015.[8]"; var sentenceDetector = new EnglishMaximumEntropySentenceDetector(currentDirectory + "../Resources/Models/EnglishSD.nbin"); string[] sentences = sentenceDetector.SentenceDetect(inputText); string longest = sentences.OrderByDescending(s => s.Length).First(); } } } 类,并创建我需要发送回控制器的对象。我的表单有复选框和隐藏的输入值。我现在面临的问题是这个。由剃刀呈现的复选框元素有两个输入,一个是隐藏的,另一个是显示的。当我收集表单数据时,我总是得到最后一个输入值(隐藏的一个,它总是.control_group)我怎样才能获得真正的价值?

enter image description here

发送到控制器的当前数据(一切都是假的):

false

收集这样的数据(在SO上发现类似的问题):

{"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"}]}

控制器看起来像这样:

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

2 个答案:

答案 0 :(得分:0)

根据设计,您可以在此处阅读:asp.net mvc: why is Html.CheckBox generating an additional hidden input

我可以在迭代元素时建议您执行以下操作

如果表单中有另一个具有相同名称的元素,并且它不是复选框,则跳过它。

这样你就可以收集到正确的字段。

我非常肯定您可以使用JQUERY处理此问题,如果没有,请发布JSFIDDLE以便我们为您提供帮助。

答案 1 :(得分:0)

Razor语法总是为单选按钮创建一个隐藏字段&复选框。您可以将:input选择器更改为:input:checkbox以执行任务。

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