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

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.

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

Angularjs WebApi is not working in Asp.net MVC Entity Framework

This error is Occur after running the web application. this is picture of inspect elements of google chrome.
See Image
See Second Image
i want to us entity framework
here is class code... when i comment the
public virtual List tblproduct { get; set; } and
public virtual List tblproduct { get; set; } this its working perfetcly how to completety use entity framework mvc in it
[Table("tblCatagory")]
public class AddCatagory
{
public int Id { get; set; }
[StringLength(56)]
public string CataName { get; set; }
public virtual List<Product> tblproduct { get; set; }
//public virtual List<AddSubCatagory> tblsubcatagory { get; set; }
}
[Table("tblSubCatagory")]
public class AddSubCatagory
{
public int Id { get; set; }
[StringLength(56)]
public string SubCataName { get; set; }
public int AddCatagoryId { get; set; }
public virtual AddCatagory tblcatagory { get; set; }
public virtual List<Product> tblproduct { get; set; }
}
product class code
[Table("tblProduct")]
public class Product
{
public int Id { get; set; }
[StringLength(56)]
public string ProductName { get; set; }
[StringLength(156)]
public string ProductDes { get; set; }
public int ProductQty { get; set; }
public double ProductRate { get; set; }
public double Inches { get; set; }
public DateTime Date { get; set; }
public int AddCatagoryId { get; set; }
public int AddSubCatagoryId { get; set; }
public virtual AddCatagory tblcatagory{ get; set; }
public virtual AddSubCatagory tblsubcatagory{ get; set; }
}
wepapi controller
public List<Product> Getproducts()
{
var result = db.products.ToList();
return result;
}
angularjs code..
GetAllPro();
function GetAllPro() {
$http.get("/api/Products").then(function (response) {
$scope.Pro = response.data;
}, function () {
alert("Error")
})
}

post array of string from angular js controller to asp controller

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();
}

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

Web ApI Entity Framework (Code First) Value not appearing in database

My database will run correctly, and I can input the data manually via SQL Server, however, when I try and pass the value in via my API (testing using Postman), the value won't pass into the database, it appears as "NULL".
I have a reports and a bookings tables.
This is the code for the reports:
public class Report
{
public Report()
{
Injuries = new List<Injury>();
this.Bookings = new HashSet<Booking>();
}
public int Id { get; set; }
public string Club1 { get; set; }
public string Club2 { get; set; }
public virtual ICollection<Injury> Injuries { get; set; }
public virtual ICollection<Booking> Bookings { get; set; }
}
Bookings:
public class Booking
{
//public Booking()
//{
// Reports = new List<Report>();
//}
public int Id { get; set; }
public string Club { get; set; }
public string PlayerName { get; set; }
public string PlayerNumber { get; set; }
public string Reason { get; set; }
public string Description { get; set; }
//public int? Report_Id { get; set; }
public Nullable<int> Report_Id { get; set; }
public virtual Report Report { get; set; }
//public virtual ICollection<Report> Reports { get; set; }
}
Controller:
//POST: api/Reports
[ResponseType(typeof(Report))]
public async Task<IHttpActionResult> PostReport(Report report)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
db.Reports.Add(report);
await db.SaveChangesAsync();
return CreatedAtRoute("DefaultApi", new { id = report.Id }, report);
}
I put the test information via Postman:
I'm not sure why Report_Id is showing as it's not required, however, Report_Id1 is the field that is connecting the Report and Booking together.
Since your foreign key doesn't follow convention (ReportId), you need to use the annotation [ForeignKey] or a fluent api configuration:
modelBuilder.Entity<Booking>()
.HasRequired(b => b.Report)
.WithMany(b => b.Bookings)
.HasForeignKey(p => p.Report_Id);
That is why EF is adding the second Report_ID1. https://msdn.microsoft.com/en-us/data/hh134698.aspx

Resources