Hi @Binumon George
I assume the Country and State model as below:
public class Country
{
public int CountryId { get; set; }
public string CountryName { get; set; }
}
public class State
{
public int StateId { get; set; }
public string StateName { get; set; }
public int CountryId { get; set; }
}
From your code the request body 1 and request body 2 only has one different property: CountryId, so, to receive the request body 1 and body 2, you can create a DataModel like this:
public class DataModel
{
public string DataType { get; set; }
public List<Datum> Data { get; set; }
}
public class Datum
{
public int Id { get; set; }
public string Name { get; set; }
public int CountryId { get; set; }
}
Then, in the Controller, after receiving the Json data from the request body, you can use the Linq Select statement to query the data and convert the model to Country or State, code like this:
[Route("api/[controller]")]
[ApiController]
public class AddDataController : ControllerBase
{
[HttpPost("Save")]
public IActionResult SaveData([FromBody] DataModel data)
{
if (data.DataType=="Country")
{
var countries = data.Data.Select(c=> new Country() { CountryId=c.Id, CountryName =c.Name}).ToList();
//insert countries into database.
return Ok(countries);
}
else if (data.DataType=="State")
{
var states = data.Data.Select(c => new State() { StateId=c.Id, StateName =c.Name, CountryId = c.CountryId }).ToList();
//insert states into database.
return Ok(states);
}
else
{
return new JsonResult("DataType not match");
}
}
}
The result as below:
If the request body is country:
If the request data is state:
If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.
Best regards,
Dillion