2

I am developing an Angular App with .net server and the backend is written in c#. I have formed an object by combining the data from two different forms and converted object to json string using JSON.stringify. How can i convert this json string from angular to a c# object and the object should get the values from the json string.

Please guide me. Thanks in Advance.

I used this conversion to convert json string to c# class. UPDATE: Update with controller, signalrhub and cors policy.

json object

const Root = {
    "Unit" : "mm",
    "test": [{
      "Val": this.Val1.isChecked,
      'Val1' : this.val2.isChecked,
    }],
    "test1" :{
      "sub":[{
        'val2' : this.valFormGroup.get('val2').value,
        'Val3' : this.valFormGroup.get('val3').value,
        }]
        },
}
const foo = JSON.stringify(Root);
console.log(foo);

json string.

{"Units":"mm","test":[{"Val":true,"Val1":false}], "test1":[{"Val2":"red","Val3":"5"}]}

c# class

public class Test
{
    public bool Val { get; set; }
    public bool Val1 { get; set; }
}

public class Test1
{
    public string Val2 { get; set; }
    public string Val3 { get; set; }
}

public class RootObject
{
    public string Units { get; set; }
    public List<Test> test { get; set; }
    public List<Test1> test1 { get; set; }
}

Controller

namespace angular.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class DIMController : Controller
    {

             private IHubContext<DIMHub> _hubContext;
        public DIMController(IHubContext<DIMHub> hubContext)
    {
  _hubContext = hubContext;
}
[HttpPost]

 public JsonResult Postdata(string json)
{
 // Your data variable is of type RootObject
 var data= JsonConvert.DeserializeObject<RootObject>(json);

 //Get your variables here as shown in first example. Something like:
 var unit=data.Units; 
 return Json(true);
}  

SignalR hub

namespace angular.HubConfig
{
public class DIMHub: Hub
{
 public async Task Send1 ( string message1, Root data)
{
  await Clients.All.SendAsync("Send1", message1);
}

}
}

Startup.cs

services.AddCors(options =>{
    options.AddPolicy("CorsPolicy",
    builder => builder
    .AllowAnyMethod()
    .AllowAnyHeader()
    .AllowCredentials()
    .AllowAnyOrigin());
app.UseCors("CorsPolicy");
});

Client

form(){
 var json = Root;
  $.ajax({
    type: "POST",
    cache: false,  
    dataType: "json",
    url: 'http://localhost:5001/api/DIM/Postdata',     
    data: { "json": JSON.stringify(json)},  
   // contentType: "application/json",    

  // headers : {'Content-Type': 'application/json'},
  success: function (data) {
    console.log(data)
  },
  error: function (data) {
    console.log('error in sending data...:(')
  },
  });
}

5 Answers 5

2

If you setup an ASP .NET CORE Webapi it more or less does it for you.

https://learn.microsoft.com/en-us/aspnet/core/tutorials/first-web-api?view=aspnetcore-2.2&tabs=visual-studio Checkout section: Add a Create method

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

Comments

2

Your model classes are correct in accordance to your JSON string that you have posted in the question. All you would require is to deserialize the string correctly. I am posting a code snippet specifically for your JSON string. I am using the Newtonsoft JSON library which is a popular high-performance JSON framework for .NET.

A working demo: https://dotnetfiddle.net/s2OXhT

using System;
using Newtonsoft.Json;
using System.Collections.Generic;

public class Program
{
    public static void Main()
    {
        var jsonString = @"{'Units':'mm','test':[{'Val':true,'Val1':false}], 'test1':[{'Val2':'red','Val3':'5'}]}";
        var data= JsonConvert.DeserializeObject<RootObject>(jsonString);
        Console.WriteLine(data.Units);

        foreach(var values in data.test)
        {
            Console.WriteLine(values.Val);  
            Console.WriteLine(values.Val1);
        }

        foreach(var values1 in data.test1)
        {
            Console.WriteLine(values1.Val2);    
            Console.WriteLine(values1.Val3);
        }       
    }
}

public class Test
{
    public bool Val { get; set; }
    public bool Val1 { get; set; }
}

public class Test1
{
    public string Val2 { get; set; }
    public string Val3 { get; set; }
}

public class RootObject
{
    public string Units { get; set; }
    public List<Test> test { get; set; }
    public List<Test1> test1 { get; set; }
}

Output:

mm
True
False
red
5

Update: In the above part, I have given you an example of how to deserialize your JSON string correctly. In the example below, I am giving a very basic example of how you can use AJAX to post your values as a JSON string to your Controller method. I am not very familiar with Angular so I will try my best here:

Your AJAX call would look like:

<script type="text/javascript">

const Root = {
    "Unit" : "mm",
    "test": [{
      "Val": this.Val1.isChecked,
      'Val1' : this.val2.isChecked,
    }],
    "test1" :{
      "sub":[{
        'val2' : this.valFormGroup.get('val2').value,
        'Val3' : this.valFormGroup.get('val3').value,
        }]
        },
     }

var json = Root;

//Assuming a button click event here but you can use any event 
$('#myBtn').click(function (){
    $.ajax({
        url: '@Url.Action("ProcessJSON", "Home")', // This can be a WEB API method or a Controller method. You can even call 3rd party WEB API  
        type: "POST",
        dataType: "json",
        data: { "json": JSON.stringify(json)},
        success: function (data) {
           console.log(data)
         },
         error: function (data) {
           console.log('error in sending data...:(')
         },
    });
};
</script>

Your Controller would look like something like this:

[HttpPost]
public JsonResult ProcessJSON(string json)
{
 // Your data variable is of type RootObject
 var data= JsonConvert.DeserializeObject<RootObject>(json);

 //Get your variables here as shown in first example. Something like:
 var unit=data.Units; //mm

 return Json(true);
}

13 Comments

can you please suggest how can i import the jsonsting from angular client to c# object. my jsonstring is in appcomponent.ts.
@ramkris For that you would need to setup your a web method that will process this JSON string as a payload. You can use AJAX to send your json string via your angular client.
Thanks for your time Rahul. I will check it out.
@ramkris I will update my answer with a very basic example of how you can achieve this.
I did not try it at. I am working on other issue. I will update as soon as i try the solution. Thank you very much for asking.
|
1

Try like this:

jsonString = {"Units":"mm","test":[{"Val":true,"Val1":false}], "test1":[{"Val2":"red","Val3":"5"}]}

var data= JsonConvert.DeserializeObject<RootObject>(jsonString);

Comments

1

Using ASP.NET Web Api Project

You used Root>test1 in "sub" property.

Javascript

    var Root = {
        "Unit" : "mm",
        "test": [{
          "Val": this.Val1.isChecked,
          'Val1' : this.val2.isChecked,
        }],
        "test1" :{
          "sub":[{
            'val2' : this.valFormGroup.get('val2').value,
            'Val3' : this.valFormGroup.get('val3').value,
            }]
            },
    }

 $.ajax({
        type: "POST",
        url: 'http://YouSite/api/controller/YouActionName',        
        data: Root ,
        dataType: "json",
        headers : {'Content-Type': 'application/json'},
        success: function (data) {
           console.log("Message: ",data.Message);
           console.log("Status: ", data.MyStatus);
         },
         error: function (data) {
           console.warn(data);
         },
    });

OUTPUT

Message:  transaction successful
Status:  true

ASP.NET Web Api Controller

ASP.NET WebApi automatically serializes json data

[HttpPost]
public MyResponseModel YouActionName([FromBody]MyRootObject data)
{
 var unit=data.Unit;
 var test=data.test;
 var subs=data.test1.sub;
var response = new MyResponseModel(){ Message="transaction successful", MyStatus=true};
//you can customize your return object
 return response;
}

Web Api Route

public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            // Web API routes
            config.MapHttpAttributeRoutes();

            config.Routes.MapHttpRoute(
                "DefaultApi",
                "api/{controller}/{action}/{id}",
                new {id = RouteParameter.Optional}
            );
        }
    }

Request Models

  public class Test
    {
        public bool Val { get; set; }
        public bool Val1 { get; set; }
    }

    public class Test1
    {
        public List<Sub> sub { get; set; }
    }
    public class Sub
    {
        public string Val2 { get; set; }
        public string Val3 { get; set; }
    }

    public class RootObject
    {
        public string Units { get; set; }
        public List<Test> test { get; set; }
        public List<Test1> test1 { get; set; }
    }

Response Model

 public class MyResponseModel
    {
        public string Message { get; set; }
        public bool MyStatus { get; set; }
    }

2 Comments

Hi @Faith, I have tried your solution but i am getting an error "OPTIONS localhost:5001/api/Ds/post net::ERR_EMPTY_RESPONSE zone.js:3331". can you please guide me regarding this.
@ramkris need to see the codes. This error is not related to my solution. May be the address you requested or a setting you missed. Upload your entire project to github and let's check it out.
-1

try this one

var obj=JSON.parse("yourjsonstring")

console.log(obj);

2 Comments

This does not answer the question being asked, does not provide any explanation of the code being suggested, and the code is incorrect in the first place. When answering a question make sure you have fully read the question before providing an answer.
This does not provide an answer to the question. Once you have sufficient reputation you will be able to comment on any post; instead, provide answers that don't require clarification from the asker. - From Review

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.