post array of string from angular js controller to asp controller - angularjs

I am using visual studio 2017 with asp mvc 5.0 and angularJS v1.6.10. I need to send object from angularJS to asp controller via $http service see the following code
public class Patient
{
public int Age { get; set; }
public byte Gender { get; set; }
public bool IsSmoker { get; set; }
public string[] Symptoms { get; set; }
public bool FractionWithTbPatient { get; set; }
public bool PreviousTbInfection { get; set; }
public bool Inheritedcysricfibrosis { get; set; }
public bool Inheritedasthma { get; set; }
public bool Smokermother { get; set; }
public bool OrganicDust { get; set; }
public bool FractionWithanimals { get; set; }
public bool PreviousSurgery { get; set; }
public bool Longbonebroken { get; set; }
public bool Pregnant { get; set; }
public bool CancerInfection { get; set; }
public bool LongTimeInBed { get; set; }
public bool PreviousInfectionWithPulmonaryEmbolism { get; set; }
}
and the asp controller method is the following
public class ConditionDiagnosisController : Controller{
[HttpPost]
public void GetCaseResult(Patient patient)
{
int i = 0;
i++;
}
}
and the angularJS controller is the follwoing
myApp.controller("mainController",
function ($scope, $http) {
var patient = new Object();
patient.Age = 1;
patient.Gender = 0;
patient.IsSmoker = false;
patient.Inheritedasthma = false;
patient.Symptoms = ['x','y'];
patient.Pregnant = false;
patient.FractionWithTbPatient = false;
patient.PreviousTbInfection = false;
patient.Inheritedcysricfibrosis = false;
patient.Inheritedasthma = false;
patient.Smokermother = false;
patient.OrganicDust = false;
patient.FractionWithanimals = false;
patient.PreviousSurgery = false;
patient.Longbonebroken = false;
patient.Pregnant = false;
patient.CancerInfection = false;
patient.LongTimeInBed = false;
patient.PreviousInfectionWithPulmonaryEmbolism = false;
$scope.go = function () {
$http({
method: "POST",
url: "/ConditionDiagnosis/GetCaseResult",
dataType: 'json',
data: $scope.patient,
headers: { "Content-Type": "application/json" }
});
};
});
when I send it I get in the asp method all values of the object correctly else the Symptoms variable which is a string array, I get it null. Any help?

Try with this data : JSON.stringify($scope.patient)

in the ASP.NET class, you should assign the Array in the constructor.
the issue will be that you can't assign the array so the best way is to use List
change the type of Symptoms to List and then in the constructor write this code:
public Patient(){
Symptoms = new List();
}

Related

Always getting null value when send object with fromData other value from React

I have send a formData from react app with some value and image files and i also want to send a obj with same formData on .net core api
Here is my class
[Bind]
public class ServiceInfo
{
public int id { get; set; }
[NotMapped]
public IFormFile[] ImgFile { get; set; }
[NotMapped]
public IFormFile ImgFilen { get; set; }
//public int { get; set; }
public string title { get; set; }
public string serImg1 { get; set; }
public string serImg2 { get; set; }
public string serImg3 { get; set; }
public string serImg4 { get; set; }
public int serCategoryId { get; set; }
public SerCategory serCategory { get; set; }
public string time { get; set; }
public string location { get; set; }
public string serviceClose { get; set; }
public string serviceOpen { get; set; }
public int CompanyInfoId { get; set; }
public virtual CompanyInfo companyInfo { get; set; }
public string serviceDetails { get; set; }
public string offeredServices { get; set; }
public bool active { get; set; }
public bool status { get; set; }
public string extraServices { get; set; }
public string whyUs { get; set; }
}
.net core controler:
serCategory always getting null
[Route("PotService")]
[HttpPost]
public IActionResult Post([FromForm] ServiceInfo service)
{
//using (MemoryStream stream = new MemoryStream())
//{
// ImgFile.CopyToAsync(stream);
// service.Data = stream.ToArray();
//}
if (string.IsNullOrWhiteSpace(_rootPath.WebRootPath))
{
_rootPath.WebRootPath = Path.Combine(Directory.GetCurrentDirectory(), "Images");
}
string uploadsFolder = Path.Combine(_rootPath.WebRootPath);
int index = 0;
foreach (var item in service.ImgFile)
{
index++;
if (item != null)
{
var uniqueFileName = service.title.ToString()+index.ToString()+ DateTime.Now.ToString("ddMMyyy") + "_" + item.FileName;
string filePath = Path.Combine(uploadsFolder, uniqueFileName);
switch (index)
{
case 1 :
service.serImg1 = uniqueFileName;
break;
case 2:
service.serImg2 = uniqueFileName;
break;
case 3:
service.serImg3 = uniqueFileName;
break;
case 4:
service.serImg4 = uniqueFileName;
break;
}
}
}
//bool result = _serManager.AddService(service);
foreach (var item in service.ImgFile)
{
if (item != null)
{
var uniqueFileName = service.title.ToString() + index.ToString() + DateTime.Now.ToString("ddMMyyy") + "_" + item.FileName;
string filePath = Path.Combine(uploadsFolder, uniqueFileName);
using (var fileStream = new FileStream(filePath, FileMode.Create))
{
item.CopyTo(fileStream);
}
}
}
return Ok(true);
}
And react code :
const formData = new FormData();
formData.append("id", 0);
formData.append("CompanyInfoId", activeComId);
formData.append("title", data.title);
formData.append("time", "");
formData.append("location", data.location.value);
formData.append("serviceClose", data.serviceClose.value);
formData.append("serviceOpen", data.serviceOpen);
formData.append("serviceDetails", data.serviceDetails);
formData.append("serCategoryId", data.serType.id);
formData.append("serCategory", data.serType);
formData.append("offeredServices", data.offeredServices);
formData.append("active", false);
formData.append("status", false);
formData.append("extraServices", data.extraServices);
formData.append("whyUs", data.whyUs);
formData.append("ImgFile", data.serImg1);
formData.append("ImgFile", data.serImg2);
formData.append("ImgFile", data.serImg3);
formData.append("ImgFile", data.serImg4);
for (const [key, value] of formData.entries()) {
console.log(key, value);
}
console.log(data.serType);
const res = await fetch(serPost, {
method: "POST",
body: formData,
});

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

angularjs $http is throwing error 500 (Internal Server Error) when groupby in linq is used and passed as json

angularjs $http is throwing error 500 (Internal Server Error) when groupby in linq is used and passed as json
I have 2 classes Offer and OfferDetails
public class OfferDetails
{
public long? eventid { get; set; }
public List<Offer> offer { get; set; }
}
public class Offer
{
public long OfferId { get; set; }
public string OfferType { get; set; }
public Nullable<long> EventId { get; set; }
public Nullable<decimal> OfferDiscount { get; set; }
public Nullable<int> NoofPeople { get; set; }
public Nullable<long> UserId { get; set; }
public Nullable<System.DateTime> CreatedDate { get; set; }
public Nullable<System.DateTime> UpdatedDate { get; set; }
public string CreatedIp { get; set; }
public string UpdatedIp { get; set; }
public Nullable<bool> IsActive { get; set; }
}
When I am calling the method offerdetailsjson() using angularjs $http and putting breakpoint on method offerdetailsjson() then it is running fine but $http throws error
public JsonResult offerdetailsjson()
{
List<OfferDetails> r = repository.Offers.GetAll().GroupBy(x => x.EventId).Select(x => new OfferDetails
{
eventid = x.Key,
offer = x.ToList()
}).ToList();
return Json(r);
}
<script>
angular.module('app', []).controller("OfferListCtrl", OfferListController);
OfferListController.$inject = ['$scope', '$http'];
function OfferListController($scope, $http) {
$http({
url: '/Master/offerdetails',
method: 'post',
}).then(function (response) {
debugger
alert(JSON.stringify(response.data));
}, function () { alert('Failed'); });
}
</script>
I will be thankful if someone can help me.

A circular reference was detected while serializing an object of type in AngularJs and asp.net mvc

Well I know it is well known error. There are lots of questions asked here. But after going through few questions I am not able to solve my problem I am getting this error my website.
This is my error
A circular reference was detected while serializing an object of type
My Controller Code is
[HttpGet]
public JsonResult Get(int currentPage, int recordsPerPage)
{
var pageNumber = currentPage;
var pageSize = recordsPerPage;
var begin = (pageNumber - 1) * pageSize;
var totalNumberOfRecords = db.Products.Count();
var productlist = db.Products.OrderBy(r => r.ProductID).Skip(begin).Take(pageSize).ToList();
db.Configuration.ProxyCreationEnabled = false;
//var productlist = db.Products.ToList();
var product = new { Product = productlist, TotalRecords = totalNumberOfRecords };
return Json(new { Products = productlist, RecordCount = totalNumberOfRecords }, JsonRequestBehavior.AllowGet);
}
My Angular Controller Code is this
function GetProducts() {
var productResult = productService.getProduct($scope.currentPage, $scope.recordsPerPage);
productResult.then(function (result) {
console.log("d",data);
if (result.data != '' || result.data != null) {
if (result.data != null || result.data != '') {
$scope.Products = result.data;
}
else if (result.data = 0) {
$scope.message = "No Product Found"
}
}
});
};
And Angular Service code is this
this.getProduct = function (currentPage, recordsPerPage) {
return $http.get('/Home/Get?currentPage=' + currentPage + '&recordsPerPage=' + recordsPerPage);
// return $http.get('/Home/Get');
};
I am missing something but I am unable to get that. Any expert please help me in this.. I spend my whole night with this error. I try every solution of stackoverflow which I read but nothing works for me
Here is My Model
namespace StylesStore.Models
{
using System;
using System.Collections.Generic;
public partial class Product
{
public Product()
{
this.Carts = new HashSet<Cart>();
this.OrdersDetails = new HashSet<OrdersDetail>();
}
public int ProductID { get; set; }
public Nullable<int> SKU { get; set; }
public Nullable<int> VendorProductID { get; set; }
public string ProductName { get; set; }
public string ProductDescription { get; set; }
public Nullable<int> SupplierID { get; set; }
public Nullable<int> CategoryID { get; set; }
public Nullable<int> QuantityPerUnit { get; set; }
public decimal UnitPrice { get; set; }
public Nullable<int> MSRP { get; set; }
public Nullable<int> AvailableSize { get; set; }
public string AvailableColor { get; set; }
public Nullable<int> Size { get; set; }
public string Color { get; set; }
public Nullable<int> Discount { get; set; }
public Nullable<int> UnitWeight { get; set; }
public Nullable<int> UnitsInStock { get; set; }
public string UnitsInOrder { get; set; }
public string Picture1 { get; set; }
public string Picture2 { get; set; }
public string Picture3 { get; set; }
public string Picture4 { get; set; }
public Nullable<decimal> ShippingCharges { get; set; }
public string Note { get; set; }
public Nullable<bool> InStock { get; set; }
public Nullable<int> CatID { get; set; }
public Nullable<decimal> wieght { get; set; }
public Nullable<int> totalview { get; set; }
public Nullable<int> Disable { get; set; }
public Nullable<System.DateTime> EntryDate { get; set; }
public virtual ICollection<Cart> Carts { get; set; }
public virtual Category Category { get; set; }
public virtual ICollection<OrdersDetail> OrdersDetails { get; set; }
public virtual Supplier Supplier { get; set; }
}
}
You should not serialize your entity objects. Your entity objects have virtual navigation properties which are detected by JsonSerializer. JsonSerializer thinks they are embedded properties of that object and tries to serialize them too. and this goes on. serializer finds itself trying to serialize all database. this is why your error occurs.
You should either mark fields that need to be serialized or use DTO's to serialize objects.
Note: you can use AutoMapper to map objects between Entity and DTO

How to save FormData into sql

I need to store the path of the file along with its properties into a sql database. Currently all I can do is store the file on the server. I can see the file properties in the controller but I do not know how to access them.
public class File
{
public int FileId { get; set; }
public string FileType { get; set; }
public string FileDate { get; set; }
public string FilePdf { get; set; }
public string FileLocation { get; set; }
public string FilePlant { get; set; }
public string FileTerm { get; set; }
public DateTime? FileUploadDate { get; set; }
public string FileUploadedBy { get; set; }
public string CompanyName { get; set; }
public virtual ApplicationUser User { get; set; }
}
Controller
[HttpPost]
public async Task<HttpResponseMessage> PostFile()
{
if (!Request.Content.IsMimeMultipartContent())
{
this.Request.CreateResponse(HttpStatusCode.UnsupportedMediaType);
}
string root = HttpContext.Current.Server.MapPath("~/App_Data");
var provider = new MultipartFormDataStreamProvider(root);
var result = await Request.Content.ReadAsMultipartAsync(provider);
foreach (var key in provider.FormData.AllKeys)
{
foreach (var val in result.FormData.GetValues("companyname")
.FirstOrDefault())
{
if (key == "companyName")
{
var companyName = val;
var fileDate = val;
var fileLocation = val;
var filePlant = val;
var fileTerm = val;
var fileType = val;
var fileUploadDate = val;
var fileUploadedBy = val;
}
}
}
// On upload, files are given a generic name like "BodyPart_26d6abe1-3ae1-416a-9429-b35f15e6e5d5"
// so this is how you can get the original file name
var originalFileName = GetDeserializedFileName(result.FileData.First());
var uploadedFileInfo = new FileInfo(result.FileData.First().LocalFileName);
string path = result.FileData.First().LocalFileName;
//Do whatever you want to do with your file here
//db.Files.Add();
db.SaveChanges();
return this.Request.CreateResponse(HttpStatusCode.OK, originalFileName);
}
private string GetDeserializedFileName(MultipartFileData fileData)
{
var fileName = GetFileName(fileData);
return JsonConvert.DeserializeObject(fileName).ToString();
}
public string GetFileName(MultipartFileData fileData)
{
return fileData.Headers.ContentDisposition.FileName;
}
Try using a function like this. You can replace with
private object GetFormData<T>(MultipartFormDataStreamProvider result)
{
if (result.FormData.HasKeys())
{
var unescapedFormData = Uri.UnescapeDataString(result.FormData
.GetValues(0).FirstOrDefault() ?? String.Empty);
if (!String.IsNullOrEmpty(unescapedFormData))
return JsonConvert.DeserializeObject<T>(unescapedFormData);
}
return null;
}
Use it like this
File file = GetFormData(result);
The main line of code you want is:
JsonConvert.DeserializeObject<File>(result.FormData.GetValues(0).FirstOrDefault());

Resources