在asp.net中使用jquery ajax插入值到数据库中
问题描述:
在下面的代码中,我尝试使用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);
}
}
答
检查你的URL地址,也许它应该看起来像这样:
~/UnitDetails.aspx/InsertData
或
~/UnitDetails/InsertData/
,并检查您是路过的数据,尝试通过jQ传递静态数据而不提取值可能会有一些错误。 STH这样的:
{'UnitType': 'type', 'UnitTypeCode': 'typeCode'}
+0
我试过了,但它不工作 – 2014-12-06 10:56:08
答
这里是您的解决方案
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)
希望有帮助!
这里是一个很好的教程,通过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