2014-12-06 35 views
0

在下面的代碼中,我嘗試使用jquery ajax將值插入到數據庫中。在我的情況下,我調用jquery ajax按鈕單擊。但它不會調用webmethod.Pls幫助我糾正這個問題。在asp.net中使用jquery ajax插入值到數據庫中

UnitDetails.aspx

<script type="text/JavaScript" 
src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script> 

<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true"> 
</asp:ScriptManager> 
function MyFunction() { 

       $.ajax({ 
        type: "POST", 

        url: "UnitDetails.aspx/InsertData", 
        data: "{'UnitType':'" + $("#<%=txtUnitTypeName.ClientID%>").val() + "','UnitTypeCode':'" + $("#<%=txtUnitTypeShortCode.ClientID%>").val() + "'}", 
        contentType: "application/json; charset=utf-8", 
        dataType: "json", 
        async: "true", 
        cache: "false", 
        success: function (msg) { 
         alert("Success"); 
         // On success     
        }, 
        Error: function (x, e) { 
         alert("Fail"); 
         // On Error 
        } 
       }); 
      } 
<input name="data[UnitType][Name]" type="text" class="autofocus"maxlength="255" id="txtUnitTypeName" runat="server" /> 

<input name="data[UnitType][ShortCode]" type="text" maxlength="5" id="txtUnitTypeShortCode" runat="server" /> 



[WebMethod] 
     public static void InsertData(string UnitType, string Code) 
     { 
      try 
      { 
       MastersClient Uinsert = new MastersClient(); 
       Dictionary<string, string> UnitVal = new Dictionary<string, string>(); 
       UnitVal.Add("UnitTypeName", UnitType.ToString()); 
       UnitVal.Add("UnitTypeShortCode", Code.ToString()); 
      } 
      catch (Exception ex) 
      { 
       string strMsg = "Error message : " + Environment.NewLine + "Date : " + DateTime.Now.ToString("dd/MMM/yyyy HH:mm:ss") + Environment.NewLine + "Error : " + ex.Message + Environment.NewLine; 
       Logger objErrorHandler = new Logger(); 
       objErrorHandler.MsgType = MessageType.MailAndEventLog; 
       objErrorHandler.RaiseError(strMsg, ex); 
      } 
     } 
+0

這裏是一個很好的教程,通過jQuery插入數據到數據庫ajax​​ http://codepedia.info/2016/01/insert-data-using-jquery-ajax-in-asp-net-csharp-database-ms-sql服務器/ – 2016-02-20 14:15:59

回答

0

檢查你的URL地址,也許它應該看起來像這樣:

~/UnitDetails.aspx/InsertData 

~/UnitDetails/InsertData/ 

,並檢查您是路過的數據,嘗試通過jQ傳遞靜態數據而不提取值可能會有一些錯誤。 STH這樣的:

{'UnitType': 'type', 'UnitTypeCode': 'typeCode'} 
+0

我試過了,但它不工作 – 2014-12-06 10:56:08

0

這裏是您的解決方案

 data: "{'UnitType':'" + $("#<%=txtUnitTypeName.ClientID%>").val() + "', 
'UnitTypeCode':'" + $("#<%=txtUnitTypeShortCode.ClientID%>").val() + "'}", 

你在你的發佈數據中第二個參數是UnitTypeCode

,而在你的服務你的第二個參數是code這是不對的,應該是相同的

public static void InsertData(string UnitType, string Code) 

應該是

public static void InsertData(string UnitType, string UnitTypeCode) 

希望有幫助!

相關問題