2013-12-01 4 views
1

Я пытаюсь реализовать jQuery-метод ajax, который публикует всю форму. Теперь я получил jquery успешно выполнить код на стороне сервера, но серверная переменная NameValue [] formVars пуста! Я не могу понять, почему. Может ли кто-нибудь помочь в этом вопросе. спасибоОшибка с использованием jQuery для данных формы POST для веб-службы ASP.NET ASMX AJAX

Но мой вызов jquery ajax всегда возвращает пустую ошибку.

Вот мой Javascript код

<script type="text/javascript"> 

    $(document).ready(function() { 


     var MaxInputs = 8; //maximum input boxes allowed 
     var InputsWrapper = $("#InputsWrapper"); //Input boxes wrapper ID 
     var AddButton = $("#AddMoreFileBox"); //Add button ID 

     var x = InputsWrapper.length; //initlal text box count 
     var FieldCount = 1; //to keep track of text box added 

     $(AddButton).click(function (e) //on add input button click 
     { 
      if (x <= MaxInputs) //max input box allowed 
      { 
       FieldCount++; //text box added increment 
       //add input box 
       $(InputsWrapper).append('<div><input type="text" name="mytext[]" id="field_' + FieldCount + '" value="Text ' + FieldCount + '"/><a href="#" class="removeclass">&times;</a></div>'); 
       x++; //text box increment 
      } 
      return false; 
     }); 

     $("#main_container").on("click", ".removeclass", function (e) { //user click on remove text 
      //alert("clicked"); 
      if (x > 1) { 
       $(this).parent('div').remove(); //remove text box 
       x--; //decrement textbox 
      } 
      return false; 
     }) 


     // Add the page method call as an onclick handler for the div. 
     $("#Result").click(function() { 
      $.ajax({ 
       type: "POST", 
       url: "testingJqueryAjax.aspx/GetDate", 
       data: "{'msg':'hello'}", 
       contentType: "application/json; charset=utf-8", 
       dataType: "json", 
       success: function (msg) { 
        // Replace the div's content with the page method's return. 
        $("#Result").text(msg.d); 
       } 
      }); 
     }); 
     function sendRegistration() { 
      var arForm = $("#form1").serializeArray(); 

      $.ajax({ 
       type: "POST", 
       url: "testingJqueryAjax.aspx/ExecuteRegistration", 
       contentType: "application/json", 
       data: JSON.stringify({ formVars: arForm }), 
       dataType: "json", 
       success: function (result) { 
        var jEl = $("#msgdiv"); 
        jEl.html(result.d).fadeIn(1000); 
        setTimeout(function() { jEl.fadeOut(1000) }, 5000); 
        // $("#msgdiv").text(result.d); 
       }, 
       error: function (ts) { 
        alert("An error occurred: " + ts.responseText); 
       } 
      }); 
     } 


     $("#btnSend").click(function() { 
      alert("btnSend clicked"); 
      sendRegistration(); 
     }); 
    }); 
</script> 

Вот мой код

[WebMethod] 
    public static string ExecuteRegistration(NameValue[] formVars) 
    { 
     StringBuilder sb = new StringBuilder(); 

     sb.AppendFormat("Thank you {0}, <br/><br/>", 
         HttpUtility.HtmlEncode(formVars.Form("txtName"))); 

     sb.AppendLine("You've entered the following: <hr/>"); 

     foreach (NameValue nv in formVars) 
     { 
      // strip out ASP.NET form vars like _ViewState/_EventValidation 
      if (!nv.name.StartsWith("__")) 
      { 
       if (nv.name.StartsWith("txt") || nv.name.StartsWith("lst") || nv.name.StartsWith("chk")) 
        sb.Append(nv.name.Substring(3)); 
       else 
        sb.Append(nv.name); 
       sb.AppendLine(": " + HttpUtility.HtmlEncode(nv.value) + "<br/>"); 
      } 
     } 
     sb.AppendLine("<hr/>"); 

     string[] needs = formVars.FormMultiple("lstSpecialNeeds"); 
     if (needs == null) 
      sb.AppendLine("No Special Needs"); 
     else 
     { 
      sb.AppendLine("Special Needs: <br/>"); 
      foreach (string need in needs) 
      { 
       sb.AppendLine("&nbsp;&nbsp;" + need + "<br/>"); 
      } 
     } 

     return sb.ToString(); 
    } 

стороне сервера Вот HTML-

<hr /> 
<div id="msgdiv"> 
    divmsg : 
</div> 
<div id="div1" class="errordisplay" style="display: none"> 
</div> 

<div> 
    <div class="label">Name:</div> 
    <div> 
     <asp:TextBox runat="server" ID="txtName" /> 
    </div> 
</div> 
<div> 
    <div class="label">Company:</div> 
    <div> 
     <asp:TextBox runat="server" ID="txtCompany" /> 
    </div> 
</div> 
<div> 
    <div class="label"></div> 
    <div> 
     <asp:DropDownList runat="server" ID="lstAttending"> 
      <asp:ListItem Text="Attending" Value="Attending" /> 
      <asp:ListItem Text="Not Attending" Value="NotAttending" /> 
      <asp:ListItem Text="Maybe Attending" Value="MaybeAttending" /> 
      <asp:ListItem Text="Not Sure Yet" Value="NotSureYet" /> 
     </asp:DropDownList> 
    </div> 
</div> 
<div> 
    <div class="label"> 
     Special Needs:<br /> 
     <small>(check all that apply)</small> 
    </div> 
    <div> 
     <asp:ListBox runat="server" ID="lstSpecialNeeds" SelectionMode="Multiple"> 
      <asp:ListItem Text="Vegitarian" Value="Vegitarian" /> 
      <asp:ListItem Text="Vegan" Value="Vegan" /> 
      <asp:ListItem Text="Kosher" Value="Kosher" /> 
      <asp:ListItem Text="Special Access" Value="SpecialAccess" /> 
      <asp:ListItem Text="No Binder" Value="NoBinder" /> 
     </asp:ListBox> 
    </div> 
</div> 
<div> 
    <div class="label"></div> 
    <div> 
     <asp:CheckBox ID="chkAdditionalGuests" Text="Additional Guests" runat="server" /> 
    </div> 
</div> 

<hr /> 

<input type="button" id="btnSend" value="Send Registration" /> 

Я следую tutorial по следующей ссылке, а использования asmx, я использовал статический метод aspx. теперь, выполняя код, я могу успешно выполнить код на стороне сервера, но он не берет никаких данных из веб-формы.

НазваниеValue [] formVars переменная не имеет записей. ЗАЧЕМ??

Обновление по этому вопросу, я поставил код на пустой странице aspx, затем программа работает. Первоначально я положил его на страницу aspx, построенную на главной странице. Таким образом, похоже, что-то связано с главной страницей.

ответ

0

мне удалось решить эту проблему, проблема была вызвана ссылкой Java Script на главной странице, что моя страница тестирования унаследованная от.

0

Комментария в этом блоке:

// [System.Web.Script.Services.ScriptService] 
+0

Не могли бы вы рассказать об этом, спасибо. –