为什么我的模型值为空,如果我不包装脚本代码中的单击事件

Why is my model value null if I don’t wrap the script code in a click event?

本文关键字:代码 脚本 包装 事件 单击 模型 我的 如果 为什么      更新时间:2023-09-26

我在视图的末尾有一个javascript,它创建了一个选定复选框的数组。提交表单的按钮允许我访问表单集合和其他参数。如果我将单击事件附加到同一按钮以运行java脚本,则javascript中的数据将被发送,但表单收集参数为空。如果我从脚本中删除click函数,我的脚本模型参数为空,其他参数ok。

这是我的脚本数据如何得到控制器得到。

我使用一个模型:命名空间SchoolIn。视图模型{公共类registrmentoptionsvm{

  public virtual string OptionID{ set;get;}
   public virtual string UserChoice { set;get;}

     }
 }

 [HttpPost]
    public ActionResult Edit(int id, FormCollection formCollection, String[] options,     List<EnrollmentOptionsVM> model, String[] instructorString, String[] selectedteacher,string[]  selectedCourses, Student student, string course, Enrollment enrolls, Assignment assignment, String[]  searchString)

 <script type="text/javascript">
        var $checkboxes = $('input[type="checkbox"]');

        $(document).ready(function () {
               var options= [];
 $.each($checkboxes, function () {
    if ($(this).is(':checked')) {
  var item={ "UserChoice" : "checked", "OptionID": "YouCanSetIDHere"};
  }
  else
    {
      var item={ "UserChoice" : "unchecked", "OptionID": "YouCanSetIDHere"};
    }
     options.push(item);
  })
   $.ajax({ type: 
  'POST', url: '@Url.Action("Edit","Student")',
            contentType: 'application/json',
            data: JSON.stringify(options)
        }).done(function (html) {
         });
       alert('success')
        });

        </script>

这是编辑帖子的签名。

 [HttpPost]
    public ActionResult Edit(int id, FormCollection formCollection, String[] options,   List<EnrollmentOptionsVM> model, String[] instructorString, String[] selectedteacher,string[] selectedCourses, Student student, string course, Enrollment enrolls, Assignment assignment, String[] searchString)

我在脚本中放置了一个alert(),以确保它运行正常。为什么我的模型值为空,如果我不包装脚本代码在点击事件?

如果你的脚本在head标签中,那么当你引用复选框var $checkboxes = $('input[type="checkbox"]');时,它们还没有在页面中,所以$checkboxes将是一个空的jQuery对象

您需要将$checkboxes = $('input[type="checkbox"]');放入$(document).ready函数

好了,我明白了。虽然我的Javascript和Razor发送到相同的动作,但它们的参数不会在同一时间发送到同一post。为了解决这个问题,我创建了一个不同的操作,并使用click函数来触发事件。