MVC and Angular 2 k_backingfield problems during Mumbai training

This week during MVC and Angular training in Mumbai one of our students got a typical JSON issue when he was trying to get data from MVC WEBAPI. So he was posting using Angular 2 HTTP and from the server side MVC WebAPI was sending data back to the angular 2 client.

Below is the error screen shot of what the student was getting. We were expecting just supplierAmount , SupplierCode and SupplierName but he was also getting k__BackingField with it.

ash

The main cause of this issue was C# auto properties. Auto properties are c# properties which are just written with set and get and without private variables. When you have auto properties then the default WEB API JSON converter adds those funny & notorious backing fields.

publicclassSupplier
{ 
publicstring SupplierCode { get; set; }

publicstring SupplierName { get; set; }

publicdecimal  SupplierAmount { get; set; }
}

So the solution was to go and set the WEB API formatter to JsonFormatter. Once we did this everything was rocking ☻.

var formatter = GlobalConfiguration.Configuration.Formatters.JsonFormatter;
            formatter.SerializerSettings = newJsonSerializerSettings
            {
                Formatting = Formatting.Indented,
                TypeNameHandling = TypeNameHandling.Objects,
                ContractResolver = newCamelCasePropertyNamesContractResolver()
            };

Do not miss our next MVC core and Angular 2 Training in Mumbai happening next week Saturday and Sunday.

Comments

comments

This entry was posted in Angular 2 training, Angular Mumbai Training, MVC, MVC Training in Mumbai and tagged , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *