views:

32

answers:

1

I need to make a post ajax request, where in i need to pass entity classes as parameter.

for eg:

[OperationContract]
    [WebInvoke(Method = "POST",
           BodyStyle = WebMessageBodyStyle.Wrapped,
           ResponseFormat = WebMessageFormat.Json
    )]
    public bool SaveEmployee(Employee employee)
    {
        //inserting the data to database.
    }

here my entity class is Employee which has 2,3 properties exposed, say empId,employeename and age.

These informations i need to pass from javascript.

   function SaveEmployee() {

var employeename='test';
var age=23;
var empid=34534;
//these data's i need to pass to the ajax method.
        var am = new Proxy();
        am.invoke("SaveEmployee", { **here how can i pass my entity Employee?** }, function(response){
             if (response) {

can i do something like this in the javascript?

var employee=new Employee();
employee.Name=employeename;
employee.Age=age;
employee.EmpId=empid;
and  am.invoke("SaveEmployee", { "Employee":employee },
A: 

Here's a sample I put together that POSTs an entity to a WCF REST service (using jQuery on the client side). If you're not using jQuery, I think you'll still see how to handle it.

Here's the HTML & JavaScript:

<html xmlns="http://www.w3.org/1999/xhtml"&gt;
<head>
    <title></title>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"&gt;&lt;/script&gt;
</head>
<body>
    Name: <input type="text" id="name" /><br />
    Desc: <input type="text" id="desc" /><br />
    <button id="submit">Send!</button>

    <script type="text/javascript">
        $(function () {
            $("#submit").click(function (e) {
                e.preventDefault();
                var theData = {};
                theData["Name"] = $("#name").val();
                theData["Desc"] = $("#desc").val();
                $.ajax({
                    type: "POST",
                    url: "ProdService.svc/product/add",
                    data: JSON.stringify(theData),
                    dataType: "json",
                    contentType: "application/json",
                    success: function (data) {
                        alert(data);
                    },
                    error: function (e, t, x) {
                        alert(t);
                    }
                });
            });
        });
    </script>
</body>
</html>

The key things to note is that I'm setting the content type of the request to application/json. That's key for WCF so it knows what's being sent up.

My service is defined as such:

[OperationContract]
[WebInvoke(Method="POST", ResponseFormat=WebMessageFormat.Json, RequestFormat=WebMessageFormat.Json,
    BodyStyle=WebMessageBodyStyle.Bare, UriTemplate="product/add")]
String AddProduct(Product p)
{
    return "Got " + p.Name;
}

And my entity is like this:

[DataContract]
public class Product
{
    [DataMember()]
    public String Name { get; set; }
    [DataMember()]
    public String Desc { get; set; }
}

My web.config is set up like this:

<system.serviceModel>
    <behaviors>
        <endpointBehaviors>
            <behavior name="WebApplication2.ProdServiceAspNetAjaxBehavior">
              <webHttp />
            </behavior>
        </endpointBehaviors>
    </behaviors>
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true"
        multipleSiteBindingsEnabled="true" />
    <services>
        <service name="WebApplication2.ProdService">
            <endpoint address="" behaviorConfiguration="WebApplication2.ProdServiceAspNetAjaxBehavior"
                binding="webHttpBinding" contract="WebApplication2.ProdService" />
        </service>
    </services>
</system.serviceModel>

The key in the web.config is that my endpointBehavior uses webHttp instead of enableWebScript. Other than that, this is pretty much an out-of-the-box configuration.

So the keys are that my payload is a JavaScript object literal converted to a JSON-ized string. My service is expecting the request format to be JSON, and since my Product class is decorated with the DataMember and DataContract attributes, it can deserialize my payload to a Product class instance.

I hope this helps. Please let me know if you have other questions and I'll update my answer accordingly.

David Hoerster