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...:(')
},
});
}