How to send two Array objects using http in AngularJS? - javascript

How to receive two parameters as an array in http action(List abc, List) xyz.
after that attempt I use a model class. lik
public class ItemAndChecque
{
public List<SaleItem> saleitem { get; set; }
public List<itemChecqe> itemchecq { get; set; }
}
public IHttpActionResult TowArrayValue(List<ItemAndChecque> abc)
I did many attempt to solve it but not... Some one can send me any Solution.

Your arrays need to be grouped in one object array:
var Indata = {saleitem: $scope.saleitem,itemchecq: $scope.itemchecq}
$http({
url: "someAPI",
method: "POST",
data: Indata
});
Add ItemAndChecque as model class to your backend.
Then you can receive it in your API Controller like this:
public void Post(ItemAndChecque request)
{
var productRepository = new ProductRepository();
var newProduct = productRepository.Save(request.product);
}
Here request contains 2 props with values of saleitem and itemchecq
Edit: based on the comment of #Icycool

Related

How to pass a list of objects in Razor to an ASP.Net Core Controller via ajax? [duplicate]

This question already has answers here:
How to convert View Model into JSON object in ASP.NET MVC?
(9 answers)
Closed 5 months ago.
I have an Ajax call which has a list of parameters. One of them is a list of objects from the Model. I am having trouble trying to prepare the data to send to the Controller. Currently, it's like this:
const result = await $.ajax({
type: "POST",
url: "/PayrollAudit/SaveFundFindings",
data: {
'fundFindingsGridRows': DATA,
'revisionDateExists': #Model.revisionDateExists.ToString().ToLower(),
'rev': #Model.rev.ToString().ToLower(),
'deficiency': #Model.deficiency,
'principalAndInterest': #Model.principalAndInterest,
'newAudit': #Model.newAudit.ToString().ToLower(),
'auditStartDate': moment('#Model.auditStartDate').format('MM/DD/YYYY'),
'billingEntityFindingsTitle': '#Model.billingEntityFindingsTitle',
'delinquency20': #Model.delinquency20,
'billingEntityNo': '#Model.billingEntityNo',
'revisionSentToFundsDate': moment('#Model.revisionSentToFundsDate').format('MM/DD/YYYY'),
'V3FundOptions': #Model.V3FundOptions
}
});
When this is run, I get the following error in the browser debug console:
Uncaught SyntaxError: Unexpected number (at PayrollAudit:2617:66)
Here is what the code looks like in the console:
Controller:
public IActionResult SaveFundFindings(
List<FundFindingsGridRow> fundFindingsGridRows,
bool revisionDateExists,
bool rev,
bool settlement,
decimal deficiency,
decimal principalAndInterest,
bool newAudit,
DateTime auditStartDate,
string billingEntityFindingsTitle,
decimal delinquency20,
string billingEntityNo,
DateTime revisionSentToFundsDate,
List<FundOption> V3FundOptions
)
{
// Do things...
}
FundOption Class:
public partial class FundOption
{
public string ClientCode { get; set; }
public string LvwColTitle { get; set; }
public int ColOrder { get; set; }
public string DbFieldName { get; set; }
}
I understand that using #Model is going to return the name of the collection and not the objects in the collection. So, what do I need to do here to properly send this data to the controller?
Like #Heretic Monkey suggested in the comments, you need to serialize the list to JSON. Add #using System.Text.Json in your view and then use #Html.Raw(Json.Serialize(Model.V3FundOptions)):
const result = await $.ajax({
type: "POST",
url: "/PayrollAudit/SaveFundFindings",
data: {
'fundFindingsGridRows': DATA,
'revisionDateExists': #Model.revisionDateExists.ToString().ToLower(),
'rev': #Model.rev.ToString().ToLower(),
'deficiency': #Model.deficiency,
'principalAndInterest': #Model.principalAndInterest,
'newAudit': #Model.newAudit.ToString().ToLower(),
'auditStartDate': moment('#Model.auditStartDate').format('MM/DD/YYYY'),
'billingEntityFindingsTitle': '#Model.billingEntityFindingsTitle',
'delinquency20': #Model.delinquency20,
'billingEntityNo': '#Model.billingEntityNo',
'revisionSentToFundsDate': moment('#Model.revisionSentToFundsDate').format('MM/DD/YYYY'),
'V3FundOptions': #Html.Raw(JsonSerializer.Serialize(Model.V3FundOptions))
}
});

How to dynamically call an ActionResult in your API by using an Ajax-call?

I have coded in the StartUp.cs the following code for calling my API.
services.AddHttpClient("MyApi", c =>
{
#if DEBUG
c.BaseAddress = new Uri("https://localhost:12345");
#else
c.BaseAddress = new Uri("https://myApi.com");
#endif
But when I want to call the ActionResult by using an Ajax-call, he can't find the API.
alert(apiUrl);
$.ajax({
url: apiUrl + '/MyApiProcesses/GetSomething',
type: 'POST',
So I have written this variable in a js-file.
var apiUrl = 'https://localhost:12345';
//var apiUrl = 'https://myApi.com';
I want to know if it is possible to write it dynamically. If you declare it in the startup, you don't have to declare it twice?
If you need to use urls in ajax or httpclient, I usually do it this way, but it takes several steps to get a string from appsettings.
Create AppUrl section in appsettings.json
"AppUrl": {
"DevUrl": "http//..",
"ProductUrl": "http//..",
.... another urls if needed
},
2.Create class for this section
public class AppUrlSettings
{
public string DevUrl{ get; set; }
public string ProdUrl{ get; set; }
....another urls
}
configure settings in startup
var appUrlSection=Configuration.GetSection("AppUrl");
services.Configure<AppUrlSettings>(appUrlSection);
var urls = appUrlSection.Get<AppUrlSettings>();
services.AddHttpClient("MyApi", c =>
{
#if DEBUG
c.BaseAddress = new Uri(urls.DevUrl);
#else
c.BaseAddress = new Uri(urls.ProdUrl;
#endif
});
now you can use them like this
public class MyController:Controller
{
private readonly IOptions<AppUrlSettings> _appUrls;
public MyController (IOptions<AppUrlSettings> appUrls)
{
_appUrls = appUrls;
}
public IActionResult MyAction()
{
var model= new Model
{
DevUrl=_appUrls.Value.DevUrl;
...
}
}
}
you can then use urls as hidden fields.
or you can get urls from model in javascript directly:
var devUrl = #Html.Raw(Json.Encode(#Model.DevUrl));
.....
Or if you need the urls in many places, it can make sense to create a special service that you can inject directly in the views you need

Why Javascript POST Request to ASP.NET controller action getting NULL parameter?

The parameters of my ASP .NET controller method stays null when I send a XmlHttpRequets from my JavaScript file. The JavaScript debugger shows that the request sends successfully. Why is It not working?
JavaScript function:
function BuyBook(title) {
var xmlHttp = new XMLHttpRequest();
xmlHttp.open("POST", "home/BuyBook", true);
xmlHttp.setRequestHeader("Content-Type", "multipart/form-data");
var order = { BookTitle: title, Quantity: document.getElementById("quantity").value };
xmlHttp.send(JSON.stringify({ order: order }));
console.log(xmlHttp.responseText);
}
Controller method:
[HttpPost]
public IActionResult BuyBook(Models.Order order)
{ .... }
Models.Order class:
public class Order
{
[Required]
public string BookTitle { get; set; }
[Range(1,100)]
public int Quantity { get; set; }
}
Try the following things:
Check that the class signature matches the JSON being sent. For above example, the JSON being sent would look like
{ "BookTitle": title, "Quantity": "value" }
Also I see that the class defines Quantity as int, so use parseInt() to convert Quantity value into int. By default document.getElementById(..).value would give a string.
let quantity = parseInt(document.getElementById("quantity").value);
var order = { BookTitle: title, Quantity: quantity };
Use Content-Type as application/json
Add [FromBody] attribute to the model
BuyBook([FromBody]Models.Order order)
Send the order object like below.
xmlHttp.send(order);
OR
xmlHttp.send(JSON.stringify(order));
Update your method like this:
[HttpPost]
public IActionResult BuyBook([FromBody] Models.Order order)
{ .... }
You can find more information here

send multiple objects via ajax (using angular)

I have a list of user inputs in an object 'data'. (for e.g data.username, data.password, data.age)
i am passing the data object to backend like this using angular.
var submits = "=" + JSON.stringify(data);
$.ajax({
type: "POST",
url: serviceURL,
data: submits
});
I am passing two more objects. selections and grid. how can i pass all these three together in one ajax call ? or do i have to transfer it independently. will it affect the performance if i transfer these details separately.
can i do something like this to send the object together in one ajax call?
var data = {};
data[0] = data1;
data[1] = data2;
How can i retrieve it separately at the server side using c# if at all they are passed together.
Heres the 3 objects that i need to pass
data -->> ["Raul","New York","31"]
selections-->> ["dy.txt","my.txt","yy.txt"]
grid--> ["sesion","id"]
Assuming you have a view model like this in your server side
public class CreateUserViewModel
{
public string UserName{set;get;}
public string Location {set;get;}
public int Age {set;get;}
}
public class RegisterViewModel
{
public CreateUserViewModel User {set;get;}
public List<string> Selections {set;get;}
public List<string> Grid {set;get;}
}
and an MVC action method like this
public ActionResult Create(RegisterViewModel model)
{
// read model and save and return some JSON response
}
You can simply build the javascript object which matches the structure of the view model and post it using angualr's $http service. No need to worrry about setting content-Type or Json stringifying it. Angualr will take care of it.
var model={ User : {} ,Selections :[], Grid=[] };
model.User.Age =23;
model.User.UserName ="test";
model.User.Location="New York";
model.Selections.push("dy.txt");
model.Selections.push("some.txt");
model.Grid.push("session");
model.Grid.push("id");
var url="replcaeUrltoYourActionMethodHere";
$http.post(url, model)
.then(function(response)
{
// do something with the response
// var result= response.data
});
You can send multiple objects / variables in ajax with:
var submits = "=" + JSON.stringify(data);
$.ajax({
type: "POST",
url: serviceURL,
data: {submits : submits, data1:data1, data2:data2}
});
In your C# you can access data1 and 2 in the same way as you handle submits now.
Depending of what is in data1 and data2 you might need to stringify it first.
second option:
You can also if you want to (but it is more ugly) use the stringify on everything at once and only pass the string:
data = {};
data["data1"] = data1;
data["data2"] = data2;
var submits = "=" + JSON.stringify(data);
Are you using WebApi or MVC on the server? If so, the simplest approach would be to create a class which holds the 3 entities you need to send and leverage the built-in model-binding
So in your example you list what looks to be a user form, selections and grids. I'm not really sure what the last two are but an example Model might look something like this:
public class UserSubmissionViewModel
{
public UserSubmissionViewModel() { }
public UserFormModel User {get;set;}
public SelectionsModel Selections { get; set; }
public GridModel Grids { get; set; }
}
Then on your web api controller or your MVC controller you'd have a method such as this:
public async Task<IHttpActionResult> Submit(UserSubmissionViewModel model)
And your javascript would resemble something roughly like this:
var toSend = {"UserFormModel":data, "SelectionsModel":selections, "GridModel":grids};
$.ajax({
type:"POST",
data:toSend, //<--- you might need to JSON.stringify this, cant test this code at the moment
url:serviceURL //<-- Calls your Submit method on the controller
});

How can I send complex JavaScript object to ASP.net WebMethod?

I'm trying send my client-side custom object (JavaScript) to ASP.net Web Method. I use jQuery Ajax command to perform this operation.
There a example of my object:
function Customer() {
this.Name = "";
this.Surname = "";
this.Addresses = new Array();
}
I load data with this method:
function buildCurrentCustomer() {
var currentCustomer = new Customer();
/** General Info **/
currentCustomer.Name = $("#Name").val();
currentCustomer.Surname = $("#Surname").val();
currentCustomer.Addresses = new Array();
currentCustomer.Addresses["HOME"] = $("#adHome").val();
currentCustomer.Addresses["OFFICE"] = $("#adOffice").val();
return currentCustomer;
}
And finally I send data with this code:
$.ajax({
type: "POST",
url: "../_layouts/CustomerManager/MasterPage.aspx/SetCustomer",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: "{customer: " + JSON.stringify(currentCustomer) + "}",
cache: false,
success: function (result) {
},
error: function (ex) {
WriteToConsole(ex.responseText);
}
});
My server-side methods is like that:
[WebMethod]
public static bool SetCustomer(CustomerModel Customer)
{
//My code...
}
and my CustomerModel class is like that:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Common.Model.JavaScriptModel
{
public class CustomerModel
{
/** General Info **/
public string Name {get;set;}
public string Surname {get;set;}
public Dictionary<string, string> Addresses { get; set; }
}
}
The problem is that when I execute Ajax Call server-side method doesn't execute. If I change signature of server-side method in:
public static bool SetCustomer(List<CustomerModel> Customer)
SetCustomer method is executed but the List is empty.
Why have I this problem? Where can I find documentation about this functionality?
Thanks
first, if you use the data like this
data: "{customer: " + JSON.stringify(currentCustomer) + "}",
on the code behind, you need to take the same parameter customer and not Customer, so this
public static bool SetCustomer(CustomerModel Customer) { ... }
needs to be changed to
public static bool SetCustomer(CustomerModel customer) { ... }
second, your Customer object in the javascript is like this if translated to asp.net
string Name;
string Surname;
List<string> Addresses;
but your class in the code behind for Addresses is using
Dictionary<string, string>
thus causing your data from client side can't be parsed in the server side and return an error to the client side, so you need to change your Addresses class to
public List<string> Addresses { get; set; }
and lastly, your code inside buildCurrentCustomer for the Addresses is being set like this
currentCustomer.Addresses = new Array();
currentCustomer.Addresses["HOME"] = $("#adHome").val();
currentCustomer.Addresses["OFFICE"] = $("#adOffice").val();
this will never add a value to Addresses since it's type is an array, but you set the value to it as if it was an object, so if you want to stick to use an array, you need to change it to
currentCustomer.Addresses = new Array();
currentCustomer.Addresses.push($("#adHome").val());
currentCustomer.Addresses.push($("#adOffice").val());
*Note:
use this if you want to use the Addresses as an array, but if you need the Addresses to be an object that contains HOME and OFFICE, I'll Edit the answer
Edit:
perhaps you can use a javascript object like this
currentCustomer.Addresses = {};
currentCustomer.Addresses["Home"] = $("#adHome").val();
currentCustomer.Addresses["Office"] = $("#adOffice").val();
to make the equivalent for Dictionary<string,string> but if it didn't work you could change your Addresses to class too like this
public List<Address> Addresses { get; set; }
and add class Address
public class Address
{
public string Home {get;set;}
public string Office {get;set;}
}
I myself never used a Dictionary myself, so I don't know if it's the same
You can change your source code like this..
AJAX-
data: JSON.stringify({'customer':currentCustomer});
ASP.net Web Method-
[WebMethod]
public static bool SetCustomer(object customer)
{
CustomerModel CM = new CustomerModel();
_Serializer = new JavaScriptSerializer();
_StringBuilder = new StringBuilder();
_Serializer.Serialize(customer, _StringBuilder);
CM = _Serializer.Deserialize<CustomerModel>(_StringBuilder.ToString());
}
Note that you have to initialize _Serializer and the _StringBuilder properties at the top of the page as global variables...
public static JavaScriptSerializer _Serializer;
public static StringBuilder _StringBuilder;

Categories