tags:

views:

572

answers:

2

I have a simple WCF service that I'm exposing using a .svc. The service has some related DataContract classes that are used with the ServiceContracts. When calling a method that gets some data, the json that comes back has all the properties just as you'd expect.

My question is how can I get a new instance of one of these DataContract objects in javascript.

<asp:ScriptManager ID="ScriptManager1" runat="server">
  <Services>
    <asp:ServiceReference 
      Path="./Service1.svc" />
  </Services>
</asp:ScriptManager>

<script>
// what I'd like to be able to do in javascript
var myInstance = new MyNamespace.MyDataContractClassName();
myInstance.someProperty = "Prop Value";
</script>
+1  A: 

If you browse to ./Service1.svc/js you can see the exact client proxy script that is generated by the server.

At the end of this file you should see lines that register your data contract types as client types - this just makes them available in the client type system and lets you call a well-known constructor, but it doesn't actually code their properties, because you can set any arbitrary properties on any object in JavaScript.

The code you have actually written is therefore correct, assuming that the namespace and class declaration matches what is in the proxy code, but you can verify that yourself.

A: 

Thanks @Sam, I was hoping that there was a way that all the properties could be created so that when I did new MyDataContractClassname(); I could have a nice complete object I could pass around and didn't have to test for existence of properties and such - just treat it like an object I got from a service that returns the DataContract. If say I have a method that displays the contents of that object to a user, and sometimes it is showing a new one and sometimes showing one from the service, it would be nice to just assume all properties are there just like you would if you instantiated a hand written "class"

jayrdub