can we pass array to post request in react using axios? - c#

let assume,
companyDetail is an object, and I have to pass list of company details to API.
so can I d sent array of object in post request like this:-
axios.post("",);
note API is made in ASP.NET Core Web API.
what type of data can we send ?

You can send an array of objects as long as the endpoint expect to receive this type of data.
With axios:
const companyDetails = [
{ ... },
{ ... },
{ ... },
];
axios.post("https://myapi.com/companydetails", companyDetails)
.then(response => {
console.log(response.data);
})
.catch(error => {
console.log(error);
});

Yes you can pass data as array of object companyDetail but its depends on how API request body is created in backend. If API wants request body in some other custom variable lets as reqBody the you have to assign your companyDetail to reqBody
axios.post("endpoint", {reqBody: companyDetail})
If API wants request body in companyDetail itself then:
axios.post("endpoint", {companyDetail})

CompanyDetail is an object, and I have to pass list of company details
to API. so can I d sent array of object in post request like this:-
axios.post("",);Note API is made in ASP.NET Core Web API. What type of
data can we send ?
Well, to begin with your first concern, yes we definitely can post list of object as axios.post("",) fashion. Considering your scenario we can write that snippet as following:
Let's assume, we have model as below:
Model:
public class CompanyDetails
{
public int CompanyId { get; set; }
public string Name { get; set; }
public string Email { get; set; }
}
Asp.net core Web API:
[Route("api/[controller]")]
[ApiController]
public class AxiosWebApiController : ControllerBase
{
[HttpPost]
[Route("CompanyDetails")]
public async Task<IActionResult> CompanyDetails(List<CompanyDetails> companyDetails)
{
// Do whatever you like here
return Ok(companyDetails);
}
}
What type of data can we send ?
Well, its up to you, if your controller accept list of object as Model just like this List<CompanyDetails> companyDetails then you can do as following.
Axios Request:
#section Scripts
{
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script>
const CompanyId = "CompnayId:";
const Name = "Name:";
const Email = "Email:";
const companyDetails = [];
for (let i = 1; i <= 10; i++) {
const companyObject = {
CompanyId: CompanyId + i,
Name: Name + i,
Email: Email + i
}
companyDetails.push(companyObject);
}
console.log(companyDetails);
axios.post("http://localhost:5094/api/AxiosWebApi/CompanyDetails", companyDetails);
</script>
}
Note: If your controller accept [FromForm] then append as FormData() just like formData.append("CompanyId", 1); then push to your array object.
In addition, please check your browser console if the object posted accordingly as following:
Output:

Related

.NET Core API gets null from Angular POST

I'm trying to POST data from Angular to my .NET Core API, but the incoming data is always null. See my code:
Here is my POST from Angular:
public insertCategory(categoryToInsert: ICategoryDTO): Observable<ICategoryDTO> {
const body: string = JSON.stringify(categoryToInsert);
return this.httpClient.post<ICategoryDTO>(this.apiURL + 'Categories/new', categoryToInsert);
}
ICategoryDTO being an object like this:
export interface ICategoryDTO {
Id: number;
Name: string;
}
export default ICategoryDTO;
//exemple object:
{Id: null, Name: "yyuyuy"}
This is what my API endpoint looks like on the .NET Core side:
[HttpPost("new")]
[ProducesResponseType(201)]
[ProducesResponseType(400)]
[ProducesResponseType(409)]
[ProducesResponseType(500)]
public IActionResult CreateWithAuthor([FromBody] CategoryDTO data)
{
var a = 1;
return Ok(this._iCategoryBusiness.CreateWithAuthor(data));
}
CategoryDTO being defined by this class:
using System;
namespace Back.DTO
{
public class CategoryDTO
{
public int Id { get; set; }
public string Name { get; set; }
}
}
My problem: I have a breakpoint at var a = 1 and on that breakpoint data is always null when performing the post from my front-end. Doing it from Swagger works.
What I have tried: I have tried to stringify my object before passing it, which did nothing. I have also tried to pass a header along, both with stringified and non-stringified object, which did not work either. I changed the ICategoryDTO Id type from string to number but that did nothing.
Here's the header I have tried:
header = new HttpHeaders()
.set('Content-type', 'application/json');
With a request like this:
public insertCategory(categoryToInsert: ICategoryDTO): Observable<ICategoryDTO> {
const body: string = JSON.stringify(categoryToInsert);
return this.httpClient.post<ICategoryDTO>(this.apiURL + 'Categories/new', body, {headers: this.header});
}
Didn't work, same result.
Don't know what I'm doing wrong.
I fixed it by making my Id parameter not null, but 0 instead. I guess this makes sense because it isn't nullable on the .NET end. This took me two hours.

Communication between HttpClient.PostAsJsonAsync and MVC controller actions

I have a C# controller that should make an asyncronous call to another remote controller sending a simple object (model):
HttpClient clientHTTP = new HttpClient();
myModel model = new myModel();
model.Id = 100;
model.data = "this is data";
var json = Newtonsoft.Json.JsonConvert.SerializeObject(model);
clientHTTP.BaseAddress = new Uri("http://REMOTE_IP/");
clientHTTP.PostAsJsonAsync("/WebcastNotify/Heat", json)
.ContinueWith((postTask) => postTask.Result.EnsureSuccessStatusCode());
The remote controller:
public class WebcastNotifyController : Controller
{
public ActionResult Heat(myModel model)
{
// allways recieve model.Id = 0 and model.data = null
}
}
And the simple model:
public class modeloWebCast
{
public int Id { get; set; }
public string data { get; set; }
}
Why I getting allways and empty object at remote controller (model.id = 0, model.data=null)
Like peopple suggested, If i pass the model variable directly, I recieve null object (not object with null properties like before) in the controller.
I tried to use a simple html page to test:
function Send()
{
var Url = "#Url.Action("Heat", "WebcastNotify")";
$.ajax(
{
type: "post",
url: Url,
ajaxasync: true,
data: {modelo:{ Id: 100, data: "this is the data"}},
success: function (result) {
$("#CapaInfo").html(result);
}
})
}
And with this code the object is sent to the controller perfectly.
What can i doing wrong?
PostAsJsonAsync() takes an object to serialize as JSON.
You're passing it a string (which happens to be serialized JSON), so it serializes that to a JSON string ("...").
You need to pass it the actual object.
I believe the PostAsJsonAsync method accepts a normally typed value and does not expect it to have already been serialized.
See the MSDN page.
Try passing the model variable directly.

C# consume Angular 4 class

hou would i consume the following request in my C# web Api.
Here is my Request:
this._http.post(
this.url + 'api/Test',
{ auth: this.authClass},
{ headers: this.header }
).map(
(res) => res.json()
).subscribe(
(res) => {
console.log("VALUE RECEIVED: ", res);
})
Here is my AuthClass:
export class Auth{
username:string = "";
password:string = "";
}
I have the same class in c# and need to know how do i go about receiving the class as a whole in c#.
I tried:
[HttpPost]
public IHttpActionResult login(HttpRequestMessage request)
{
var jsonString = await request.Content.ReadAsStringAsync();
var model = JsonConvert.DeserializeObject<auth>(jsonString);
return Ok();
}
My problem is that it can't parse the json to auth. My json string getting send currently looks like this.
{
"auth": {
"username": "admin",
"password": "admin1"
}
}
If its just
{
"username": "admin",
"password": "admin1"
}
then it works without any problems. But i need it to consume the first json example
about receiving the class as a whole in c#.
You wouldn't get the class. The recommended wire transfer is JSON and it will just give you the Object properties.
More
Lookup JSON serialization. The internet is full of examples with C# + AngularJS.
Arno,
You should receive a json object in your web api method.
Then use Json.Net to convert your json object to the C# object you desire.
Hope it helps.
So the answer was to wrap the auth class inside another class.
public class authReq
{
public auth request { get; set; }
}
public class auth
{
public string username { get; set; }
public string password { get; set; }
}
And then i deserialize the authReq like so.
var model = JsonConvert.DeserializeObject<register>(jsonString);

'Error 405 - Method not Allowed' when sending Ajax POST request in ASP.NET Web API

I am designing a simple Web API service that takes the inputs on an html form, turns those inputs into json, and then sends that to a Web API. I am working with ASP.NET Web API in Visual Studio 2017. Here is some of my code to help me explain better:
This is my controller method that I am calling:
[HttpPost]
public AssessModel PostAssessment ([FromBody] AssessModel assess)
{
//Do something
return assess;
}
This is the model (simplified) that I'm using:
public class AssessModel
{
public Guid capitalassetassessmentid { get; set; }
public string ownerid { get; set; }
/*... Many more properties of int, bool, ect here ...*/
public string name { get; set; }
public string building { get; set; }
}
And finally this is the ajax call that I am using in my scripts:
$("form#my-form").submit(function (e) {
//First line here takes all fields and puts them in an array
var formArray = $(this).serializeArray();
//Second line takes that array and puts it into json format.
var jsonObj = JSON.stringify(formArray);
//Send request
$.ajax({
type: "POST",
url: "api/assessment/PostAssessment",
data: jsonObj,
contentType: "application/json",
dataType: "json",
success: function (jsonObj) {
$("#results").html(jsonObj.d);
}
});
});
So I am calling this ajax request when I submit a form. This ajax request should send my json as a string to the controller method but instead when I press submit I get an Error 405 - Method not Allowed. I am unsure why I am not allowed to send a POST verb to a controller method with the tag HttpPost.
It's also worth mentioning that my form tag is like this:
<form id="my-form" class="form" method="POST">
Any thoughts? Do I need to clarify anything? Let me know.
Try
var data = {};
var formArray = $('form#my-form').serializeArray();
for(var i in array)
{
data[formArray[i].name] = formArray[i].value;
}
var jsonObj = JSON.stringify(data);

Invalid output produced using JSON serialization

I'm trying to convert a .NET object into a JSON string, because I want to be able to read the content of this object in the client side.
Here is my controller code:
public ActionResult Index()
{
IRightsManager rightsInfo = new RightsManager();
string userId = "ynz362897";
string json = JsonConvert.SerializeObject(rightsInfo.GetSectorsForUser(userId));
Session["test"] = json;
return View();
}
GetSectorsForUser returns an object which have only one attributes, a list of of another object. Here is the model:
public class Sector
{
public string Code { get; set; }
public string Name { get; set; }
public Sector(string code, string name)
{
this.Code = code;
this.Name = name;
}
}
public class RightsList
{
public IList<Sector> Sectors;
public RightsList(IList<Sector> sectors)
{
this.Sectors = sectors;
}
}
Here is GetSectorsForUser code:
public RightsList GetSectorsForUser(string userId)
{
IRightsManagerDB rightsManager = new RightsManagerDB();
RightsList rightsList = new RightsList(rightsManager.GetSectorsForUser(userId));
return(rightsList);
}
The result currently produced by my code is:
"{\"Sectors\":[{\"Code\":\"01\",\"Name\":\"FME\"},{\"Code\":\"02\",\"Name\":\"DML\"}]}"
Which is unreadable with a for in jQuery client side. I am stuck on this for hours, and I cant find any solutions.
Here is the client code:
var sectors = #Session["Sectors"];
$.each(sectors, function (i, item) {
$('#comboSector').append($('<option>', {
text: item.Name,
value : item.Code
}));
});
If you're sending the object through AJAX...
ASP.NET MVC handles JSON serialization for you. This means that you don't need the:
string json = JsonConvert.SerializeObject(rightsInfo.GetSectorsForUser(userId));
line. What happens is that you serialize the object yourself, and then ASP.NET MVC serializes it one more time, leading to the actual result, that is a string serialized as JSON. In other words:
The first serialization leads to {"Sectors": ...,
The serialization of the previous string leads to "{\"Sectors\": ....
If you're embedding the object in JavaScript within HTML...
It seems like this is what you are actually doing, and:
var sectors = #Session["Sectors"];
is a Razor file. This is a very weird approach (mixing languages, dynamically generating JavaScript, accessing the session from your view¹), but, well, let's assume you know what you are doing.
What happens here is that sectors variable points to a string which contains the JSON-serialized object, not the object itself. If you need to get the object, do:
var sectorsObj = JSON.parse(sectors);
$.each(sectorsObj, ...
JSON.parse decodes a JSON-serialized object. Similarly, JSON.stringify converts an object to its JSON representation.
¹ Accessing the session from your view like you do is not only an abuse of the MVC model and refactoring-unfriendly, but also technically wrong. Limit the view to the contents of the model, and eventually the view bag, when relevant. Avoid using global variables, session, request/response object, etc.
#MainMa Thanks for your answer. Like you said, it was not very clear technically for me. I did a bit of research and clean up my code according to standards. Now that I have a better understanding of Ajax, here is how I fixed my problem.
This is my ajax request client side.
$(document).ready(function () {
$.ajax({
url: '/Home/GetSectors',
type: 'GET',
dataType: 'json',
success: function (json) {
$.each(json, function (idx, sector) {
$('#comboSector').append($('<option>', {
text: sector.Name,
value: sector.Code
}));
})
},
error: function () {
}
});
})
Which is answered by my controller server side:
[HttpGet]
public JsonResult GetSectors()
{
Sector[] sectors = sectorManager.GetSectorsForUser("cn873284").ToArray();
return Json(sectors, JsonRequestBehavior.AllowGet);
}
Now my combo is initialized with parameter sent by the server. No more use of Session.

Categories

Resources