Ajax post jSon data in Request object - request

I am passing a json data using jQuery to a Ajax call. I want to read this json in my Application_BeginRequest function on global.ascx for some puspose.
Where can i find this data in "Request" object.
I found that the Questystring and the Form of Request object. both are empty.
Calling ajax function as below using jQuery
Regards
Umesh
var inputData = "{'ID':'" + ID + "', 'Code':'" + Centre +"'}";
var pageURL = window.location.protocol + "//" + window.location.host +
"/webmethod.aspx/MyFunction"
$.ajax({
type: "POST",
url: pageURL,
data: inputData,
contentType: "application/json; charset=utf-8",
dataType: "json",

P.S - Assuming you want to post the json data using **jquery** to your ASPX page, Adding a sample below.
function GetEmployee()
{
var jsonObj = {"Org":0 ,"Dept":0,"Desg":0,"Grp":0,"SubGrp":0,"Loc":0,"Prv":'CanViewEmployee',"CustAttrId":0,CustAttrVal:"","Status":'1' };
$.ajax({
url: 'EmployeeSearchControl.aspx/populateJsonResult',
datatype: 'json',
data:JSON.stringify(jsonObj),
method: 'Post',
success: function (data) {
if(data != null || data != "")
{
for(var i=0;i<data.length;i++)
{
addEmployeeToGrid(data[i]);
}
}
}
})
}
public class JSONRequest
{
public long Org { get; set; }
public long Dept { get; set; }
public long Desg{ get; set; }
public long Grp { get; set; }
public long SubGrp { get; set; }
public long Loc { get; set; }
public long Cat { get; set; }
public string Prv { get; set; }
public long CustAttrId { get; set; }
public string CustAttrVal { get; set; }
public string Status { get; set; }
}
protected void Page_Load(object sender, EventArgs e)
{
Response.ContentType = "application/json";
string ap = Request["org"];
HttpContext.Current.Request.InputStream.Position = 0;
string jsonString = "";
using (StreamReader inputStream = new StreamReader(this.Request.InputStream))
{
jsonString = inputStream.ReadToEnd();
}
JSONRequest masterDetails = Newtonsoft.Json.JsonConvert.DeserializeObject<JSONRequest>(jsonString);
}
Hope it helps. Please let me know if you require any other help.

Related

Data received from angularjs to MVC controller is null

Dears, I have two classes Master and detail named by Raterequest and Raterequestdetails. I have created a viewmodel contains both of them.
in Angularjs i have an object contains rate and a list contains orderdetails.
when i debug the controller the data received is null for both
here is the code
Rate request class
public class RateRequests
{
public int RateRequestsID { get; set; }
public DateTime RateRequestsDate { get; set; }
public string RateRequestName { get; set; }
public string RateRequestType { get; set; }
public string RateRequestMode { get; set; }
}
Rate request details class
public class RateRequestsLines
{
public int RateRequestsLinesID { get; set; }
public int RateRequestsID { get; set; }
[ForeignKey("RateRequestsID")]
public virtual RateRequests RateRequestsFK { get; set; }
public short FCLCNTRS { get; set; }
public short FCLCNTRSSIZE { get; set; }
public string FCLCNTRSTYPE { get; set; }
}
Rate request view model
public class RateRequestViewModel
{
public RateRequests rate { get; set; }
public IEnumerable<RateRequestsLines> ratelines { get; set; }
}
Angularjs
var linkers = angular.module("linkers", [])
.service("linkersSrv", function ($http) {
var urlBase = "/LinkersEgypt/";
this.save = function (url, ratee) {
return $http({
method: "POST",
url: urlBase + "/" + url,
data: ratee,
̶a̶s̶y̶n̶c̶:̶ ̶f̶a̶l̶s̶e̶,̶
})
};
})
.controller("linkersCon", function ($scope, linkersSrv) {
$scope.fcl = [];
$scope.addFCL = function () {
$scope.fcl.push({ FCLCNTRS: $scope.ncntrs, FCLCNTRSSIZE: $scope.csize, FCLCNTRSTYPE: $scope.ctype });
console.log($scope.fcl);
}
$scope.save = function () {
var ratee = {
rate: {
RateRequestsDate: $scope.rdate,
RateRequestName: $scope.rname,
RateRequestType: $scope.rtype,
RateRequestMode: $scope.smode
},
RateRequestsLines: $scope.fcl
};
console.log(ratee);
var promisepost = linkersSrv.save("RateRequest/AddAllRate", ratee);
promisepost.then(function () {
toastr.success("Successfully saved");
})
}
})
Rate controller
[HttpPost]
public JsonResult AddAllRate (RateRequestViewModel rate)
{
return new JsonResult();
}
Any help
Thanks in advance

Postman POST working but AngularJS post throwing 404

I'm just trying to pass some basic form data through to a web-api via AngularJS $http.
here is the function that called to send data to the API:
$http({
url: "/Portal/GenerateTimeSheets",
method: "POST",
headers: {
'Content-Type': 'application/json'
},
data: angular.toJson($scope.placementForm),
}).then(function (response) {
}), function(response) {
};
Note: if I breakpoint and copy and paste the $scope.placementForm data into postman it works completely fine, but going through a browser is throwing errors.
Here is my api:
[HttpPost]
public void GenerateTimeSheets([FromBody]PlacementModel placement)
{
Console.WriteLine("STUB");
}
and the Placement Model:
[JsonProperty(PropertyName = "candidateName")]
public string CandidateName { get; set; }
[JsonProperty(PropertyName = "clientName")]
public string ClientName { get; set; }
[JsonProperty(PropertyName = "jobTitle")]
public string JobTitle { get; set; }
[JsonProperty(PropertyName = "placementStartDate")]
public string StartDate { get; set; }
[JsonProperty(PropertyName = "placementEndDate")]
public string EndDate { get; set; }
[JsonProperty(PropertyName = "frequency")]
public string TimeSheetFrequency { get; set; }
404 Usually denotes that the url of the request is wrong, You are missing something in the url. Validate your url with the backend. Hope it helps

sending byteArray in a JSON body via angularjs http request

I want to send a post request in which the body of request is a JSON included two attributes , one of them is canvas information generated with fabricjs and the second one is a byteArray of project thumbnail. the problem is that, when I send the request , I receive null in server side.
var dataURI = this.getDataUrl($rootScope.imageType, $rootScope.imageQuality);
var strImage = dataURI.replace(/^data:image\/[a-z]+;base64,/, "");
var byteArray = covertBase64ToByteArray(strImage);
var data = {
data: {
name: name,
state: canvas.fabric.toJSON(['selectable', 'name']),
zoom: canvas.zoom,
canvasWidth: width,
canvasHeight: height,
},
typeArray: byteArray
};
$http({
method: "POST",
url: _url,
data: JSON.stringify(data),
processData: false,
transformRequest: [],
contentType: 'application/json',
})
backend Code in .Net
public IHttpActionResult InsertOrUpdateUILayout(long user_Id, long layout_Id, int userLayout_Id, int? layoutType_Id, UserlayoutContentVM data)
{
// back end code here
}
public class UserlayoutContentVM
{
public object data { get; set; }
//public string base64Image { get; set; }
public byte[] typeArray{ get; set; }
}
When posting data to the backend api you need to tell the method to read the data from the request body.
This can be done with the FromBody attribute which will map the body data to the define model.
So add all properties to one model
public class UserlayoutContentVM
{
public long user_Id { get; set; }
public long layout_Id { get; set; }
public int userLayout_Id { get; set; }
public int? layoutType_Id { get; set; }
public object data { get; set; }
public byte[] typeArray{ get; set; }
}
Then make sure the client send all data in the same structure and use the FromBody attribute in the controller method to read the values
public IHttpActionResult InsertOrUpdateUILayout([FromBody]UserlayoutContentVM data){ }

Angular js posting object to web API is null

I am posting form data to webAPI and one of object has boolean value(i.e from checkbox; Deviceselected has boolean values here in code).this object returns null in my api controller.
I tried declaring Desktop and Mobile as string in controller.That did not fix as well.
What am i missing in here?
I'm able to post other data except Deviceselected
Angualrjs controller code
$scope.SendData = function (Data) {
var GetAll = new Object();
GetAll.Redirection = Data.redirection;
GetAll.Deviceselected = new Object();
GetAll.Deviceselected.Desktop = Data.devSelected.desktop;
GetAll.Deviceselected.Mobile = Data.devSelected.mobile;
GetAll.Protocol = Data.protocol;
$http({
url: "http://localhost:61352/api/Market",
dataType: 'json',
method: 'POST',
data: GetAll,
headers: {
"Content-Type": "application/json"
}
}).then(successCallback, errorCallback);
};
})
Web API code
public class SubmitData
{
public string Redirection { get; set; }
public Deviceselected deviceSelected;
public string Protocol { get; set; }
}
public class Deviceselected
{
public Boolean Desktop { get; set; }
public Boolean Mobile { get; set; }
}
[HttpPost]
public string sendData(HttpRequestMessage request,[FromBody] SubmitData marketModel)
{
return "Data Reached";
}
Apparently it works with the same logic.1)Cleared cache 2)Run API and then load HTML

append an array to 'formdata' and how to get server side?

I'm using FormData to upload files. I also want to send an array of other data.
When I send just the image, it works fine. When I append some text to the formdata, it works fine. When I try to attach the 'ProIList' array below, everything else works fine but no array is sent
this is my angular.js file code :
this.AddPro = function (file, P) {
var formData = new FormData();
formData.append("file", file);
formData.append("name", P.name);
formData.append("description", P.description);
formData.append("ProIList", P.ProIList); // this is array list
var Response = $http.post("/Product/AddProduct", formData,
{
transformRequest: angular.identity,
headers: { 'Content-Type': undefined }
})
.success(function (res) {
Response = res;
})
.error(function () {
});
return Response;
}
this is my controller method :
[HttpPost]
[Route("AddProduct")]
public string AddProduct(string name, string description, IList<ProductItems> ProIList) // here i m not getting array
{
Products objP = new Products();
string Res = "";
objP.name = name;
objP.description = description;
db.Promotions.Add(objP); // and here add product is done now want to add ProductItems table entry so how can do
db.SaveChanges();
return Res;
}
this is my entity productItmes :
[Table("ProductItems ")]
public class ProductItems
{
[Key]
public int id { get; set; }
[ForeignKey("Products")]
public int pid {get; set;}
public int Qty { get; set; }
public Decimal Rate { get; set; }
public virtual Products Products { get; set; }
}

Resources