【问题标题】:jQuery: modify hidden form field value before submitjQuery:在提交之前修改隐藏的表单字段值
【发布时间】:2011-02-03 18:01:22
【问题描述】:

我在部分视图中有以下代码(使用 Spark):

<span id="selectCount">0</span> video(s) selected.
  <for each="var video in Model">
    <div style="padding: 3px; margin:2px" class="video_choice" id="${video.YouTubeID}">
      <span id="video_name">${video.Name}</span><br/>
      <for each="var thumb in video.Thumbnails">
        <img src="${thumb}" />
      </for>      
    </div>    
  </for>

  # using(Html.BeginForm("YouTubeVideos","Profile", FormMethod.Post, new { id = "youTubeForm" }))
  # {
  <input type="hidden" id="video_names" name="video_names" />
  <input type="submit" value="add selected"/>

  # }

  <ScriptBlock>
    $(".video_choice").click(function() { 
      $(this).toggleClass('selected');
      var count = $(".selected").length;      
      $("#selectCount").html(count);
    });

    var options = {
      target: '#videos',
      beforeSubmit: function(arr, form, opts) {
        var names = [];
        $(".selected").each(function() {

          names[names.length] = $(this).attr('id');
        });
        var namestring = names.join(",");
        $("#video_names").attr('value',namestring);
        //alert(namestring);
        //arr["video_names"] = namestring;
        //alert($.param(arr));
        //alert($("#video_names").attr('value'));
        return true;
      }
    };

    $("#youTubeForm").ajaxForm(options);

  </ScriptBlock>

基本上,我会显示一系列 div,其中包含从 YouTube API 提取的信息。我使用 jQuery 允许用户选择他们想要添加到他们的个人资料中的视频。当我提交表单时,我想用逗号分隔的视频 ID 列表填充隐藏字段。一切正常,除了当我尝试在发布的控制器中设置字段的值时,该字段返回为空。我正在使用 jQuery ajax 表单插件。

我做错了什么,不允许将我在字段中设置的值发送到服务器?

【问题讨论】:

    标签: jquery ajax asp.net-mvc-2 form-submit


    【解决方案1】:

    为你的 beforeSubmit 试试这个:

    var ids = $(".selected").map(function() { return this.id; }).get().join(',');
    $("#video_names").val(ids);
    return true;
    

    【讨论】:

    • @Jason - 尝试将beforeSubmit: function(arr, form, opts) 更改为beforeSerialize: function(),你得到值了吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-30
    • 2012-02-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多