Asked by:
Jquery is getting error while using WCF to insert data into Sql Server

Question
-
User908689340 posted
Hi,
I am using Jquery to insert data into SQL server by calling WCF URL. But it is showing error I am unable to find that.In another chrome browser it it is executing well but not hitting the sevice. I am writing the code below Please help me out.
1) Created a table with two fields empname and empdesignation in MS Sql server.
Written a WCF service.
2) Created a interface
Iservice.cs
[ServiceContract] public interface IService { [OperationContract] [WebInvoke(Method = "POST", BodyStyle = WebMessageBodyStyle.Wrapped, ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json)] string InsertUserDetails(UserDetails userInfo); }
[DataContract] public class UserDetails { string empname = string.Empty; string empdesignation = string.Empty; [DataMember] public string EmpName { get { return empname; } set { empname = value; } } [DataMember] public string EmpDesignation { get { return empdesignation; } set { empdesignation = value; } } }
4) In service.cs[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class Service : IService { public string InsertUserDetails(UserDetails userInfo) { string Message; SqlConnection con = new SqlConnection("Data Source=(local);Initial Catalog=TestDB;User ID=sa;Password=12345abc"); con.Open(); SqlCommand cmd = new SqlCommand("insert into tbl_emp(Empnames,empdesg) values(@Empnames,@empdesg)", con); cmd.Parameters.AddWithValue("@Empnames", userInfo.EmpName); cmd.Parameters.AddWithValue("@empdesg", userInfo.EmpDesignation); int result = cmd.ExecuteNonQuery(); if (result == 1) { Message = userInfo.EmpName + " Details inserted successfully"; } else { Message = userInfo.EmpName + " Details not inserted successfully"; } con.Close(); return Message; } }5) service.svc
<%@ ServiceHost Language="C#" Debug="true" Service="Service" CodeBehind="~/App_Code/Service.cs" %>
6) Default.aspx
<%@ Page Language="C#" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <script runat="server"> </script> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title></title> <script src="js/jquery.js" type="text/javascript"></script> <script type="text/javascript"> $(document).ready(function () { $('#button1').click(function () { $.ajax({ type: "POST", dataType: "json", contentType: "application/json; charset=utf-8", //Url is the path of our web method (Page name/function name) url: "http://localhost:50573/jQueryWebSite/Service.svc/InsertUserDetails", //Pass paramenters to the server side function // data: "{'Empnames':'" + "bookName" + "', 'empdesg':'" + "author"+"'}", data: "{'Empnames':'" + document.getElementById('txtUserName').value + "', 'empdesg':'" + document.getElementById('txtEmail').value + "'}", success: function (response) { alert("Record Has been Saved in Database"); }, error: function (xhr) { alert("Error"); } }); }); }); </script> </head> <body> <form id="form1" runat="server"> <div class="ui-widget"> <label for="tbAuto"> Enter UserName: </label> <asp:TextBox ID="txtUserName" runat="server" ClientIDMode="Static" Width="202px"></asp:TextBox> <br /> <br /> Email: <asp:TextBox ID="txtEmail" runat="server" ClientIDMode="Static" Width="210px"></asp:TextBox> <br /> <br /> <asp:Button ID="button1" runat="server" Text="Button" ClientIDMode="Static" /> </div> <div> </div> </form> </body> </html>
6) web.config
==========
<?xml version="1.0"?> <configuration> <appSettings/> <connectionStrings/> <system.web> <compilation debug="true" targetFramework="4.0"> <assemblies> <add assembly="System.Data.Linq, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/></assemblies></compilation> <authentication mode="Windows"/> <!--<pages controlRenderingCompatibilityVersion="3.5" clientIDMode="AutoID"/>--> <pages controlRenderingCompatibilityVersion="3.5" clientIDMode="AutoID"/></system.web> <system.serviceModel> <behaviors> <serviceBehaviors> <behavior name="ServiceBehavior"> <serviceMetadata httpGetEnabled="true"/> <serviceDebug includeExceptionDetailInFaults="true"/> </behavior> </serviceBehaviors> <endpointBehaviors> <behavior name="EndpBehavior"> <webHttp/> </behavior> </endpointBehaviors> </behaviors> <services> <service behaviorConfiguration="ServiceBehavior" name="Service"> <endpoint address="" binding="webHttpBinding" contract="IService" behaviorConfiguration="EndpBehavior"/> </service> </services> </system.serviceModel> </configuration>
Monday, December 14, 2015 2:24 PM
All replies
-
User475983607 posted
What is the error?
Maybe a CORS error?
Monday, December 14, 2015 2:56 PM -
User908689340 posted
Hi mgebhard,
Thanks for reply no its same problem I have added in web.config and Glabal.asax
Attaching the screenshot of headers
Thanks for your suggestions
Monday, December 14, 2015 4:25 PM -
User475983607 posted
What is the error?
Monday, December 14, 2015 5:57 PM -
User908689340 posted
Not getting any error.
I am thinking that it is not hitting the service.
please guide
Tuesday, December 15, 2015 5:49 AM -
User908689340 posted
Done little changes and now i am getting error like this for Response body in Developer tools
{"ExceptionDetail":{"HelpLink":null,"InnerException":{"HelpLink":null,"InnerException":null,"Message":"The token '\"' was expected but found '''.","StackTrace":" at System.Xml.XmlExceptionHelper.ThrowXmlException(XmlDictionaryReader reader, String res, String arg1, String arg2, String arg3)\u000d\u000a at System.Xml.XmlExceptionHelper.ThrowTokenExpected(XmlDictionaryReader reader, String expected, Char found)\u000d\u000a at System.Runtime.Serialization.Json.XmlJsonReader.ReadServerTypeAttribute(Boolean consumedObjectChar)\u000d\u000a at System.Runtime.Serialization.Json.XmlJsonReader.ReadAttributes()\u000d\u000a at System.Runtime.Serialization.Json.XmlJsonReader.ReadNonExistentElementName(StringHandleConstStringType elementName)\u000d\u000a at System.Runtime.Serialization.Json.XmlJsonReader.Read()\u000d\u000a at System.Xml.XmlBaseReader.IsStartElement()\u000d\u000a at System.Xml.XmlBaseReader.IsStartElement(XmlDictionaryString localName, XmlDictionaryString namespaceUri)\u000d\u000a at System.ServiceModel.Dispatcher.DataContractJsonSerializerOperationFormatter.IsStartElement(XmlDictionaryReader reader, XmlDictionaryString elementName, XmlDictionaryString elementNamespace)\u000d\u000a at System.ServiceModel.Dispatcher.DataContractJsonSerializerOperationFormatter.ValidateTypeObjectAttribute(XmlDictionaryReader reader, Boolean isRequest)\u000d\u000a at System.ServiceModel.Dispatcher.DataContractJsonSerializerOperationFormatter.DeserializeBody(XmlDictionaryReader reader, MessageVersion version, String action, MessageDescription messageDescription, Object[] parameters, Boolean isRequest)\u000d\u000a at System.ServiceModel.Dispatcher.OperationFormatter.DeserializeBodyContents(Message message, Object[] parameters, Boolean isRequest)\u000d\u000a at System.ServiceModel.Dispatcher.OperationFormatter.DeserializeRequest(Message message, Object[] parameters)","Type":"System.Xml.XmlException"},"Message":"The formatter threw an exception while trying to deserialize the message: Error in deserializing body of request message for operation 'InsertUserDetails'. The token '\"' was expected but found '''.","StackTrace":" at System.ServiceModel.Dispatcher.OperationFormatter.DeserializeRequest(Message message, Object[] parameters)\u000d\u000a at System.ServiceModel.Dispatcher.DemultiplexingDispatchMessageFormatter.DeserializeRequest(Message message, Object[] parameters)\u000d\u000a at System.ServiceModel.Dispatcher.UriTemplateDispatchFormatter.DeserializeRequest(Message message, Object[] parameters)\u000d\u000a at System.ServiceModel.Dispatcher.CompositeDispatchFormatter.DeserializeRequest(Message message, Object[] parameters)\u000d\u000a at System.ServiceModel.Dispatcher.DispatchOperationRuntime.DeserializeInputs(MessageRpc& rpc)\u000d\u000a at System.ServiceModel.Dispatcher.DispatchOperationRuntime.InvokeBegin(MessageRpc& rpc)\u000d\u000a at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage5(MessageRpc& rpc)\u000d\u000a at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage41(MessageRpc& rpc)\u000d\u000a at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage4(MessageRpc& rpc)\u000d\u000a at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage31(MessageRpc& rpc)\u000d\u000a at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage3(MessageRpc& rpc)\u000d\u000a at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage2(MessageRpc& rpc)\u000d\u000a at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage11(MessageRpc& rpc)\u000d\u000a at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage1(MessageRpc& rpc)\u000d\u000a at System.ServiceModel.Dispatcher.MessageRpc.Process(Boolean isOperationContextSet)","Type":"System.ServiceModel.Dispatcher.NetDispatcherFaultException"},"ExceptionType":"System.ServiceModel.Dispatcher.NetDispatcherFaultException","Message":"The formatter threw an exception while trying to deserialize the message: Error in deserializing body of request message for operation 'InsertUserDetails'. The token '\"' was expected but found '''.","StackTrace":" at System.ServiceModel.Dispatcher.OperationFormatter.DeserializeRequest(Message message, Object[] parameters)\u000d\u000a at System.ServiceModel.Dispatcher.DemultiplexingDispatchMessageFormatter.DeserializeRequest(Message message, Object[] parameters)\u000d\u000a at System.ServiceModel.Dispatcher.UriTemplateDispatchFormatter.DeserializeRequest(Message message, Object[] parameters)\u000d\u000a at System.ServiceModel.Dispatcher.CompositeDispatchFormatter.DeserializeRequest(Message message, Object[] parameters)\u000d\u000a at System.ServiceModel.Dispatcher.DispatchOperationRuntime.DeserializeInputs(MessageRpc& rpc)\u000d\u000a at System.ServiceModel.Dispatcher.DispatchOperationRuntime.InvokeBegin(MessageRpc& rpc)\u000d\u000a at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage5(MessageRpc& rpc)\u000d\u000a at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage41(MessageRpc& rpc)\u000d\u000a at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage4(MessageRpc& rpc)\u000d\u000a at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage31(MessageRpc& rpc)\u000d\u000a at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage3(MessageRpc& rpc)\u000d\u000a at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage2(MessageRpc& r
Tuesday, December 15, 2015 8:46 AM -
User908689340 posted
Hi mgebhard,
I am getting at last Response body as {"d":"Object reference not set to an instance of an object."}
What it means any idea you have?
Please help
Wednesday, December 16, 2015 6:22 AM -
User908689340 posted
hi i am getting error as: {"d":"Object reference not set to an instance of an object."}
Wednesday, December 16, 2015 6:26 AM -
User632428103 posted
Hi all,
i'm not an expert, but perhpas put a break point into your service and check all lines, comment perphas just the execyteNonQuery method and all works then you have probably a problem with the sql syntax => perhpas the name of the column it's not the same ..
Hope this help
Wednesday, December 16, 2015 10:04 AM