The angular app I am working on has several large input forms which span several pages. The data is added to an angular model which is a javascript object literal and sent to a webApi controller. The webApi parameter for my POST methods is a C# class (duh) with a lot of properties! Is there a utility which will generate the javascript from my C# class, so that my binding just works! I've googled this and failed even though it seems such a mundane task. As always thanks in advance.
1 Answer
You should use JSON serialize on your JS side and deserialize on your c# side.
JS:
System.Web.Script.Serialization.JavaScriptSerializer serializer =
new System.Web.Script.Serialization.JavaScriptSerializer();
string jsonParam = oSerializer.Serialize(param);
While on your c# side you should use something like, lets say your class is Person:
C#:
Person person = new JavaScriptSerializer().Deserialize<Person>(param);
see msdn documentation on serialize\deserialize json object
4 Comments
Spud
Yes I could do this this but I will still have the problem of a javascript object and a C# object needing to match so the serialize/deserialize works correctly
Or Guz
If you take your c# object and serialize it to JSON you will have a JS object that matches your c# class.
Spud
So I'm still looking for a utility or VS extension that will do this for me rather than some hacky code which spits out a text file somewhere which I then paste into my angular service/model
rythos42
We've tended to use Deserialize to return JSON from MVC Actions or inside ViewModels. You can @Html.Raw(Model.JsonString) inside your View or use it in the return from an AJAX call. No text file included!