2

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

1 Answer 1

0

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

Sign up to request clarification or add additional context in comments.

4 Comments

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
If you take your c# object and serialize it to JSON you will have a JS object that matches your c# class.
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
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!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.