簡體   English   中英

如果不將腳本代碼包裝在click事件中,為什么我的模型值為null?

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

我在視圖的末尾有一個javascript,它創建了所選復選框的數組。 提交表單的按鈕使我可以訪問表單集合和其他參數。 如果我將click事件附加到同一按鈕上以運行Java腳本,則會發送javascript中的數據,但form collection參數為null。 如果我從腳本中刪除click函數,則我的腳本模型參數為null,其他參數正常。

這是我的腳本數據到控制器的獲取方式。

我使用的是模型:命名空間SchoolIn.ViewModels {公共類EnrollmentOptionsVM {

  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(),以確保它可以正常運行。 如果不將腳本代碼包裝在click事件中,為什么我的模型值為null?

如果您的腳本在head標記中,則當您引用復選框時, var $checkboxes = $('input[type="checkbox"]'); 它們不在頁面中,因此$ checkboxes將是一個空的jQuery對象

您需要將$checkboxes = $('input[type="checkbox"]'); $(document).ready函數中

好吧,我知道發生了什么事。 盡管我的Javascript和Razor發布到相同的動作,但是它們的參數不會在同一發布中同時發送。 為了解決這個問題,我創建了一個不同的動作,並使用click函數觸發了事件。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM