How to generate angularjs model from c# class - c#

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.

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

Related

How to serialize an object in MVC 5 Razor view

I have tried to follow this post in order to create a 3 page form wizard that passes data to each page.
He uses the HTML helper serialize, to serialize an object in the view.
#Html.Serialize("wizard", Model)
However this HTML helper isn't available in MVC 5 it seems.
I found another related post to this here where he suggests using the following to serialize the object.
#Html.Hidden("otherComplexData", new Microsoft.Web.Mvc.MvcSerializer().Serialize(complexObject))
But I then get the following error
There is no argument given that corresponds to the required formal parameter 'mode' of 'MvcSerializer.Serialize(object, SerializationMode)'
It seems to want a SerializationMode, however the documented one doesn't. https://msdn.microsoft.com/en-us/library/microsoft.web.mvc.mvcserializer.serialize(v=vs.118).aspx
What direction can I go in now?
Thanks.
Here's the Serialization option you need:
https://github.com/ASP-NET-MVC/ASP.NET-Mvc-3/blob/master/mvc3/src/MvcFutures/Mvc/SerializationMode.cs
Options are Signed or EncryptedAndSigned.
You can try that and see if it will work.
There's multiple ways to encode data that will work for you. You could put the values in a hidden input using Json.Encode for the view, and Json.Decode on the server side.

Create Json in C# [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How to create JSON string in C#
I want to use google chart in mt ASP.NET MVC application. There is no mvc examples in there and datatable struct. I have never worked Json before and I must create a json like following code.
How can I create like this in C#
{"cols":[
{"id":"","label":"Month","pattern":"","type":"string"},
{"id":"","label":"Sales","pattern":"","type":"number"},
{"id":"","label":"Expenses","pattern":"","type":"number"}],
"rows":[
{"c":[
{"v":"April","f":null},
{"v":1000,"f":null},
{"v":900,"f":null},
{"c":[
{"v":"July","f":null},
{"v":1030,"f":null},
{"v":null,"f":null},
"p":null
}
I cant find easy examples about creating json in C#. Please Help me.
Thanks.
Give Json.NET a try. I think it will give you what you need.
Follow a nice article about this on code project
http://www.codeproject.com/Articles/78928/Create-JSON-from-C-using-JSON-Library
Create it as a normal class with properties, then:
var json = new JavaScriptSerializer().Serialize(myObject)
or a dynamic object:
var json = new JavaScriptSerializer().Serialize(new { property = "string" })
Well you can use DataContractJsonSerializer Class to Serializes objects to the JavaScript Object Notation (JSON) and deserializes JSON data to objects. in .net 4.0.
I hope you have checked How to create JSON string in C# and this is not duplication of the same.
Apart from that you can have option to use WCF services that produce RESTful Service and JSON data. You can check this example that is best example to suit your needs in WCF.
Another approach is if you like some built in library then Json.Net is one of the good library around on codeplex.
I would try the JSON.NET library. It has advantages of most of the serializers built into .NET in terms of both capability and performance. And I believe Microsoft will be bundling the JSON.NET library with ASP.NET 4.5 as a result.
Have a look at this code.
var oSerializer = new System.Web.Script.Serialization.JavaScriptSerializer();
oSerializer.MaxJsonLength = int.MaxValue;
string sa = oSerializer.Serialize(p); // where p is your object to serialize.
sa = "{ \"Result\": " + sa + " }";

Possible to return Json data from C# class library

I am creating a report which requires returning Lists, and Json data to a web page. I'm working with a multi-tiered application. The web project is created using MVC but the heavy lifting is done in class libraries in separate projects.
I am returning a report object to my controller from a class library but I wanted to know is it possible to return a mix of Lists and Json in the model? Ideally I would like the report model to be similar to the following:
public class Report
{
public List<TopSellers> TopSellers { get; set; }
public List<MonthlySales> MonthlySales { get; set; }
public Json ShopSales { get; set; }
}
This way, the list stuff can be rendered as normal, but the jQuery could grab the Json being return to render the graphs I'm using.
Is this possible?
I have tried to declare it similar to this however the only option I get is 'JsonReaderWriterFactory'.
My exposure of Json up until now has been null so if someone could help me out, or point me in the right direction I'd be very grateful!
Thanks.
You could use the JSON.net library to serialize your object to a json string and set it to your ShopSales property.
http://json.codeplex.com/
report.OriginalList = objectToSerialize;
var jsonStr = JsonConvert.Serialize(objectToSerialize);
report.ShopSales = jsonStr;
return report;
On the client you can use the ShopSales property with jQuery.
The only approach I see here (and which I have also adopted once) is to create an HTTP Handler in your class library which intercepts certain requests and directly writes JSON onto the response (JSON.net is worth taking a look at).
Instead of the HTTP Handler you could also take a look on whether you could directly leverage the build-in ASP.net routing mechanism.
Your class library has then to be added as reference to a front-end project (i.e. ASP.net MVC / WebForms) obviously and the handler has to be registered there.

How does MVC asp.net serialization work for Json object on Controller actions?

How does MVC asp.net serialization work for Json object on Controller actions ?
For example I have a custom object and if send an ajax request with JSON objects to the server action
public ActionResult(List<CustomObject> abc)
{
// Object is serialized automatically how MVC is doing it is the question.
}
The reason why I am asking this is that some objects of mine are not properly serialzed and hence loss of data is there , then I have to revert to the old method of string value to serializaiton.
public ActionResult(string abc)
{
JavaScriptSerializer serializer = new JavaScriptSerializer();
List<CustomObject> lstabc = serializer.Deserialize<List<CustomObject>>(abc);
}
Which I would like to avoid and secondly which are the best libraries for doing JSON object serialization MVC Asp.net ?
The deserialisation is taken care of by the model binder.
if you are finding it is not working you can create your own custom model binder and register it with the framework - this should mean you can avoid all that deserialisation noise in your controllers.
There are some links to explanations of this and how to implement a custom model binder in the following SO question:
ASP.Net MVC Custom Model Binding explanation
One of the more popular json serialisation libraries is the newtonsoft json.net library - I've used it effectively many times:
http://james.newtonking.com/pages/json-net.aspx
Good luck!

How to pass Json serialized object to javascript (ASP.NET C#)

i have a method that returns a list of serialized objects in my page code behind
private string Get()
{
JavaScriptSerializer jsonSerialiser = new JavaScriptSerializer();
string jsonString = SerializeToJason(UnavailabilityBusiness.Get(new DateTime()));
return jsonString ;
}
i would like to pass this serialized objects to javascript
function getJson()
{
??????
}
How do I do it?
You could write them out as a script, typically leveraging ClientScript.
You would want to take care to register the script so that it renders before the consuming script.
Looks like this guy wrote a utility class to do what you're trying to do (Code Project Link).
I have't really looked at it but you can get his source and have a look.
Good luck,
Patrick.

Categories