ASP.NET MVC Query not showing Distinct values - javascript

I am using the following query for use in google charts. It works well but it doesnt show distinct months. Is there a way to sum all the HoursTaken per MonthOfHoliday to avoid not having distinct values?
var querythpmpro = (from r in db.HolidayRequestForms
where r.EmployeeID == id
select new { Count = r.HoursTaken, Value = r.MonthOfHoliday.ToString() }).OrderBy(e => e.Value);
Error message from the console Uncaught (in promise) Error: Type mismatch. Value 1 does not match type string in column index 0
EDIT:
#region Total Hours Per Month
var querythpmpro = (from r in db.HolidayRequestForms
where r.EmployeeID == id
group r by r.MonthOfHoliday into g
select new { Value = g.Key, Sum = g.Sum(h => h.HoursTaken) }
).OrderBy(e => e.Value);
var resultthpmpro = querythpmpro.ToList();
var datachartthpmpro = new object[resultthpmpro.Count];
int Q = 0;
foreach (var i in resultthpmpro)
{
datachartthpmpro[Q] = new object[] { i.Value, i.Sum};
Q++;
}
string datathpmpro = JsonConvert.SerializeObject(datachartthpmpro, Formatting.None);
ViewBag.datajthpmpro = new HtmlString(datathpmpro);
#endregion
Model:
public partial class HolidayRequestForm
{
public int RequestID { get; set; }
public int EmployeeID { get; set; }
public System.DateTime StartDate { get; set; }
public System.DateTime FinishDate { get; set; }
public decimal HoursTaken { get; set; }
public string Comments { get; set; }
public int YearCreated { get; set; }
public int MonthCreated { get; set; }
public int DayCreated { get; set; }
public Nullable<int> YearOfHoliday { get; set; }
public Nullable<bool> Approved { get; set; }
public string SubmittedBy { get; set; }
public string ApprovedBy { get; set; }
public Nullable<int> WorkWeek { get; set; }
public Nullable<int> MonthOfHoliday { get; set; }
public virtual Employee Employee { get; set; }
}
Script:
function drawChartA() {
// Create the data table.
var data = new google.visualization.DataTable();
data.addColumn('string', 'Value');
data.addColumn('number', 'Count');
data.addRows(datassthpmpro);
// Set chart options
var options = {
'title': 'Holiday Hours Taken Per Month',
'width': 600,
'height': 350,
'hAxis': { title: 'Month Number' },
'vAxis': { title: 'Holiday Hours Taken' },
'is3D': true,
'legend': 'none'
};

How about grouping by MonthOfHoliday and doing the Sum on HoursTaken:
var querythpmpro = (from r in db.HolidayRequestForms
where r.EmployeeID == id
group r by r.MonthOfHoliday into g
select new { Value = g.Key, Sum = g.Sum(h => h.HoursTaken) }
).OrderBy(e => e.Value);

Related

How do i do crud from multiple tables in visual studio mvc

Hi new to visual studio and mvc in general and im trying to make a mvc crud including two tables. I have so far managed to do Create and List in index but i have having problem trying to edit,delete and show details.
Desc Class
[Table("klsm_InvoiceDesc")]
public class Desc
{
[Key]
public string InternalInvoiceNo { get; set; }
public string InvoiceNo { get; set; }
public int DescNo { get; set; }
public string Principal { get; set; }
public string ChargeCode { get; set; }
public string Quantity { get; set; }
public string Description { get; set; }
public string UnitPrice { get; set; }
public string Amount { get; set; }
public string ForeignAmount { get; set; }
public string EL1 { get; set; }
public string EL2 { get; set; }
public string ShortName { get; set; }
public string InvoiceType { get; set; }
public string PONumber { get; set; }
public string Batch { get; set; }
public string CCVBatch { get; set; }
public string PaidAmount { get; set; }
public string Paid { get; set; }
public string TT { get; set; }
public string BankCode { get; set; }
}
College Class
[Table("klsm_Invoice")]
public class College
{
[Key]
public string InternalInvoiceNo { get; set; }
public string InvoiceNo { get; set; }
[DisplayFormat(DataFormatString = "{0:dd MMM yyyy}")]
public DateTime InvoiceDate { get; set; }
public string CustomerName { get; set; }
public int Year { get; set; }
public int Month { get; set; }
public decimal Amount { get; set; }
public decimal ForeignAmount { get; set; }
public string UserCreated { get; set; }
public string UserModified { get; set; }
public int AccMonth { get; set; }
public int AccYear { get; set; }
public string AccStatus { get; set; }
public string Status { get; set; }
public string PaidStatus { get; set; }
public string Principal { get; set; }
public DateTime DateCreated { get; set; }
public DateTime DateModified { get; set; }
public string EL1 { get; set; }
public string InvoiceType { get; set; }
public string CurrencyType { get; set; }
public decimal ExchangeRate { get; set; }
public string GSTChecked { get; set; }
public DateTime PaymentSchedule { get; set; }
public string PaymentMode { get; set; }
public string CashAdvance { get; set; }
}
my home controller
public class HomeController : Controller
{
// GET: Home
DataContext db = new DataContext();
public ActionResult Index()
{
var data = db.klsm_Invoice.SqlQuery("SELECT * FROM klsm_Invoice").ToList();
return View(data);
//List<College> klsm_Invoice = db.klsm_Invoice.ToList();
//return View(klsm_Invoice);
}
// GET: Home/Details/5
public ActionResult Details(string id)
{
var data = db.klsm_Invoice.SqlQuery("SELECT * FROM klsm_Invoice WHERE InternalInvoiceNo=#p0", id).SingleOrDefault();
return View(data);
}
// GET: Home/Edit/5
public ActionResult Edit(string id)
{
var data = db.klsm_Invoice.SqlQuery("SELECT * FROM klsm_Invoice WHERE InternalInvoiceNo=#p0", id).SingleOrDefault();
return View(data);
}
// POST: Home/Edit/5
[HttpPost]
public ActionResult Edit(string id, College collection)
{
db.Entry(collection).State = System.Data.Entity.EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
// GET: Home/Delete/5
public ActionResult Delete(string id)
{
var data = db.klsm_Invoice.SqlQuery("SELECT * FROM klsm_Invoice WHERE InternalInvoiceNo=#p0", id).SingleOrDefault();
return View(data);
}
// POST: Home/Delete/5
[HttpPost]
public ActionResult Delete(string id, College collection)
{
try
{
// TODO: Add delete logic here
int result = db.Database.ExecuteSqlCommand("DELETE FROM klsm_Invoice WHERE InternalInvoiceNo=#p0", id);
db.SaveChanges();
return RedirectToAction("Index");
}
catch
{
return View();
}
}
public ActionResult Search(string InternalInvoiceNo)
{
var data = db.klsm_Invoice.SqlQuery("SELECT * FROM klsm_Invoice WHERE InternalInvoiceNo = '" + InternalInvoiceNo + "' ").ToList();
return PartialView("DefaultIndex", data);
}
// GET: Home/Create
public ActionResult Create()
{
return View();
}
[HttpPost]
public ActionResult CreateInvoice(string invoiceDetailsList, string internalInvoiceNo, string invoiceNo, DateTime invoiceDate, string customerName, int year, int month, string amount, string foreignAmount, string userCreated, string userModified, int accMonth, int accYear, string accStatus, string status, string paidStatus, string principal, DateTime dateCreated, DateTime dateModified, string el1, string invoiceType, string currrencyType, string exchangeRate, string gstChecked, DateTime paymentSchedule, string paymentMode, string cashAdvance)
{
List<Desc> detailsList = JsonConvert.DeserializeObject<List<Desc>>(invoiceDetailsList);
var addingmaster = new College();
{
addingmaster.InternalInvoiceNo = internalInvoiceNo;
addingmaster.InvoiceNo = invoiceNo;
addingmaster.InvoiceDate = Convert.ToDateTime(invoiceDate);
addingmaster.CustomerName = customerName;
addingmaster.Year = year;
addingmaster.Month = month;
addingmaster.Amount = Convert.ToDecimal(amount);
addingmaster.ForeignAmount = Convert.ToDecimal(foreignAmount);
addingmaster.UserCreated = userCreated;
addingmaster.UserModified = userModified;
addingmaster.AccMonth = accMonth;
addingmaster.AccYear = accYear;
addingmaster.AccStatus = accStatus;
addingmaster.Status = status;
addingmaster.PaidStatus = paidStatus;
addingmaster.Principal = principal;
addingmaster.DateCreated = Convert.ToDateTime(dateCreated);
addingmaster.DateModified = Convert.ToDateTime(dateModified);
addingmaster.EL1 = el1;
addingmaster.InvoiceType = invoiceType;
addingmaster.CurrencyType = currrencyType;
addingmaster.ExchangeRate = Convert.ToDecimal(exchangeRate);
addingmaster.GSTChecked = gstChecked;
addingmaster.PaymentSchedule = Convert.ToDateTime(paymentSchedule);
addingmaster.PaymentMode = paymentMode;
addingmaster.CashAdvance = cashAdvance;
db.klsm_Invoice.Add(addingmaster);
db.SaveChanges();
}
foreach (var item in detailsList)
{
Desc addingdetails = new Desc();
addingdetails.InternalInvoiceNo = item.InternalInvoiceNo;
addingdetails.InvoiceNo = item.InvoiceNo;
addingdetails.DescNo = item.DescNo;
addingdetails.Principal = item.Principal;
addingdetails.ChargeCode = item.ChargeCode;
addingdetails.Quantity = item.Quantity;
addingdetails.Description = item.Description;
addingdetails.UnitPrice = item.UnitPrice;
addingdetails.Amount = item.Amount;
addingdetails.ForeignAmount = item.ForeignAmount;
addingdetails.EL1 = item.EL1;
addingdetails.EL2 = item.EL2;
addingdetails.ShortName = item.ShortName;
addingdetails.InvoiceType = item.InvoiceType;
addingdetails.PONumber = item.PONumber;
addingdetails.Batch = item.Batch;
addingdetails.CCVBatch = item.CCVBatch;
addingdetails.PaidAmount = item.PaidAmount;
addingdetails.Paid = item.Paid;
addingdetails.TT = item.TT;
addingdetails.BankCode = item.BankCode;
//addingdetails.Id = item.Id;
db.klsm_InvoiceDesc.Add(addingdetails);
db.SaveChanges();
}
return Json(true, JsonRequestBehavior.AllowGet);
}
}
I have yet to add views for the needed help so anything will help rn

Ajax .NET Core MVC send JSON Array to Controller using Ajax

I am trying to send my data in a table to Controller by Columns, but I have tried so many methods, the parameter table is always null. Could you please give some advise on this? Thanks
Front-end Code
var data = {
"Peril": histLossesTable.getDataAtCol(0),
"OccurrenceYear": histLossesTable.getDataAtCol(1),
"Month": histLossesTable.getDataAtCol(2),
"Event": histLossesTable.getDataAtCol(3),
"InsuredLoss": histLossesTable.getDataAtCol(4),
"UnderWriterYear": histLossesTable.getDataAtCol(6),
"ReturnPeriod": histLossesTable.getDataAtCol(5),
"SelectedIndex": histLossesTable.getDataAtCol(7),
"TrendedLoss": histLossesTable.getDataAtCol(8),
"ReportingThreshold": document.getElementById('reportingThreshold').value
};
console.log(JSON.stringify(data));
$.ajax({
type: "POST",
url: "/home/test",
dataType: "json",
data: JSON.stringify(data),
contentType: "application/json; charset=utf-8",
success: function (e) {
if (e.success == true) {
console.log('POST Successful');
}
else {
console.log('POST Failed');
}
}
})
console.log(JSON.stringify(data))
{"Peril":["BF","BF"],"OccurrenceYear":["2014","2016"],"Month":["1","1"],"Event":["",""],"InsuredLoss":["10020623.440000998","5370632.38"],"UnderWriterYear":["2013","2015"],"ReturnPeriod":[12,12],"SelectedIndex":["1.801998974252194","1.6036056232964842"],"TrendedLoss":["18057153.16024929","8612376.28522618"],"ReportingThreshold":""}
Model
public class HistoricalLossTable
{
public String[] Peril { get; set; }
public int[] OccurrenceYear { get; set; }
public int[] Month { get; set; }
public String [] Event { get; set; }
public double[] InsuredLoss { get; set; }
public int[] UnderWriterYear { get; set; }
public double[] ReturnPeriod { get; set; }
public double[] SelectedIndex { get; set; }
public double[] TrendedLoss { get; set; }
public double ReportingThreshold { get; set; }
}
And Controller
[HttpPost]
public IActionResult test([FromBody]HistoricalLossTable table)
{
return View();
}
As derloopkat said in comment, you should not make the number fields as string. Try to convert your payload like below:
{
"Peril":[
"BF",
"BF"
],
"OccurrenceYear":[
2014,
2016
],
"Month":[
1,
1
],
"Event":[
"",
""
],
"InsuredLoss":[
10020623.440000998,
5370632.38
],
"UnderWriterYear":[
2013,
2015
],
"ReturnPeriod":[
12,
12
],
"SelectedIndex":[
1.801998974252194,
1.6036056232964842
],
"TrendedLoss":[
18057153.16024929,
8612376.28522618
]
}
I will suggest trying type to string based on your json and add constructor to initialize array(weird but can be an issue). Try with :
public class HistoricalLossTable
{
public string[] Peril { get; set; }
public string[] OccurrenceYear { get; set; }
public string[] Month { get; set; }
public string[] Event { get; set; }
public string[] InsuredLoss { get; set; }
public string[] UnderWriterYear { get; set; }
public string[] ReturnPeriod { get; set; }
public string[] SelectedIndex { get; set; }
public string[] TrendedLoss { get; set; }
public string ReportingThreshold { get; set; }
public HistoricalLossTable()
{
Peril = new string[2];
OccurrenceYear = new string[2];
Month = new string[2];
Event = new string[2];
InsuredLoss = new string[2];
UnderWriterYear = new string[2];
ReturnPeriod = new string[2];
SelectedIndex = new string[2];
TrendedLoss = new string[2];
}
}

Passing a list from angular to c# through http request

My method in c# receives a list as a parameter, I am trying to call this method in angular by passing it an array, but the problem is that the info doesn't reach the c# method, the list is always empty, even though there was information in the angular array.
export class StationAllocationPostModel{
idAppDeviceOwnerEntity: number;
idAppDeviceOwnerEntityOriginal: number;
idAppDeviceOwnerEntityRentalLocationId: number;
Observations: string;
selectedAppDevices: StationAllocationModel[];
}
createNewStationAllocation(selectedAppDevices: StationAllocationPostModel){
return this.post("home/CreateAppDeviceRentalLocationAllocation", selectedAppDevices, {
params: {
'idAppDeviceOwnerEntity': selectedAppDevices.idAppDeviceOwnerEntity,
'idAppDeviceOwnerEntityRentalLocationId': selectedAppDevices.idAppDeviceOwnerEntityRentalLocationId,
'Observations': selectedAppDevices.Observations,
'selectedAppDevices': selectedAppDevices.selectedAppDevices
}
});
}
public post(url: string, data: any, options = null) {
return new Promise<any>((resolve, reject) => {
let response;
this.http.post(
this.baseUrl + url,
{
data: data
},
{
headers: options ? options.headers : null,
observe: options ? options.observe : null,
params: options ? options.params : null,
reportProgress: options ? options.reportProgress : null,
responseType: options ? options.responseType : null,
withCredentials: options ? options.withCredentials : null
}
)
.subscribe(
data => {
response = data;
if (response && !response.success) {
if (response.response.ServerResponse[0].MessageType == "NOSESSIONEXCEPTION") {
localStorage.removeItem('userSession');
this.router.navigate(['/login'], { queryParams: { returnUrl: this.router.url } });
}
}
},
error => {
resolve(null);
this.handleError(url, options ? options.params : null );
console.log(error);
}, () => {
if (response) {
resolve(response);
} else {
resolve(null);
}
}
);
})
}
This is my c# method:
public Object CreateAppDeviceRentalLocationAllocation(<other params>, List<AppDeviceRentalLocationAllocationHistoryExtended> selectedAppDevices)
{
...
}
I am expecting that the c# method receives a list with elements, but it always comes out empty for some reason. The 'other params' are getting the right information, so I don't know what's wrong with the list.
Sorry for the long post, I'm new here.
Could you please form a param object on the C# method that holds the following :
public class SelectedAppDevice
{
public int idAppDevice { get; set; }
public int idAppDeviceOwnerEntity { get; set; }
public int idAppDeviceOwnerEntityRentalLocationId { get; set; }
public string Observations { get; set; }
public string DeviceId { get; set; }
public string EntityRentalLocationName { get; set; }
public DateTime CreationDate { get; set; }
public DateTime EndDate { get; set; }
public string CreatedByUserName { get; set; }
public int RentalStatus { get; set; }
public int idAppDeviceRental { get; set; }
public bool IsRentalStart { get; set; }
public bool IsRentalEnd { get; set; }
public object idNextExpectedEntityRentalLocationName { get; set; }
public object NextExpectedEntityRentalLocationName { get; set; }
public string LastKnownEntityRentingId { get; set; }
public string CallerId { get; set; }
public int RentalStatusId { get; set; }
public int DeviceStatusId { get; set; }
}
public class Data
{
public string Observations { get; set; }
public int idAppDeviceOwnerEntityRentalLocationId { get; set; }
public int idAppDeviceOwnerEntity { get; set; }
public List<SelectedAppDevice> selectedAppDevices { get; set; }
}
public class RootObject
{
public Data data { get; set; }
}
and make it as a controller method parameter :
public Object CreateAppDeviceRentalLocationAllocation(RootObject param)
{
...
}

How to display foreign key value from a model to a cascaded dropdown list in mvc5?

I'm still new to mvc5 and had very little knowledge with javascript. I know that my cascading works but I'm having trouble with the display part. What I want to do is have 2 dropdown list. 1 containing all customer names and the 2nd will have a list of their pending transactions. Basically 1st dropdown will have customer names while the 2nd will have video titles. Please check my code where I did wrong. Why I can't display the video titles. BTW I tried other properties in my transactions and I can display them. That's how I know that my cascading is not the problem.
Models
//Transaction Model
TransactionID { get; set; }
public int CustomerID { get; set; }
public virtual Customers CustomerName { get; set; }
public int VideoID { get; set; }
public virtual Videos Videos { get; set; }
public int Quantity { get; set; }
[ReadOnly(true)]
public DateTime? TransactionDate { get; set; }
[ReadOnly(true)]
public DateTime? DueDate { get; set; }
[ReadOnly(true)]
public Decimal Cost { get; set; }
[ReadOnly(true)]
public String ReturnStatus { get; set;}
//Customers Model
public int CustomerID { get; set; }
public string CustomerName { get; set; }
public string CustomerAddress { get; set; }
public string CustomerContact { get; set; }
//Video Model
public int VideoID { get; set; }
public string VideoTitle { get; set; }
public int CategoryID { get; set; }
public virtual Category VideoCategory { get; set; }
[Range(0,99)]
public int VideoIn { get; set; }
[Range(0,99)]
public int VideoOut { get; set; }
Conroller
public ActionResult CustomerList()
{
var customers = db.Customers.OrderBy(x => x.CustomerID).ToList();
if (HttpContext.Request.IsAjaxRequest())
{
return Json(new SelectList(
customers,
"CustomerID",
"CustomerName"), JsonRequestBehavior.AllowGet
);
}
return View(customers);
}
public ActionResult Transact(int cusId)
{
var transact = db.Transactions
.Where(x => x.CustomerID == cusId)
.Where(s => s.ReturnStatus == "FALSE").ToList();
if (HttpContext.Request.IsAjaxRequest())
return Json(new SelectList(
transact,
"TransactionID",
"VideoTitle"), JsonRequestBehavior.AllowGet
);
return View(transact);
}
I figure out a solution after hours of trial an error. What I did is I added a join in my query.
var transact = db.Transactions
.Where(x => x.CustomerID == cusId)
.Where(s => s.ReturnStatus == "FALSE")
.Join(db.Videos,
v => v.VideoID,
t => t.VideoID,
(transaction, videos) => new {
TransactionID = transaction.TransactionID,
VideoTitle = videos.VideoTitle }).ToList();

breezejs: navigation property not added to entity

I've configured my WebAPI ODATA service (using 5.0.0-rc1 for $expand and $select support) and everything seems to work fine but navigation properties.
The metadata does contain my navigation property (OpenPositions on Mandate) :
Then my breeze query is the following:
function search() {
var query = breeze.EntityQuery.from("Mandates").expand("OpenPositions").inlineCount();
return manager.executeQuery(query.using(service)).then(function (result) {
logger.info(result);
}).fail(function (error) {
logger.error(error);
});
}
The WebAPI controller :
[Queryable(AllowedQueryOptions= AllowedQueryOptions.All)]
public override IQueryable<Mandate> Get()
{
return new List<Mandate>() { new Mandate() {
Id = 1,
PolicyNumber = "350000000",
OpenPositions = new List<OpenPosition>(){
new OpenPosition(){ Id = 1, Amount = 2300, Mandate_Id = 1 },
new OpenPosition(){ Id = 2, Amount = 2100, Mandate_Id = 1 }
}},
new Mandate() {
Id = 2,
PolicyNumber = "240000000" ,
OpenPositions = new List<OpenPosition>(){
new OpenPosition(){ Id = 3, Amount = 2500, Mandate_Id = 2 },
new OpenPosition(){ Id = 2, Amount = 2100, Mandate_Id = 2}
}
} }.AsQueryable<Mandate>();
}
Nothing spectacular. But although my Mandate entities are coming back in the resultset, they do not have their OpenPositions collection.
As a test, if I add .select("OpenPositions") to my breeze query, then I get an error:
unable to locate property: OpenPositions on entityType: Mandate:#WebAPINoBreeze.Models
Why could that be ?
[EDIT]
query.entityType.NavigationProperties is an empty array, so that's probably a clue... It seems breeze could not build navigationproperties out of the metadata.
[EDIT]
foreign key added. problem still there:
public class Mandate
{
public int Id { get; set; }
public string PolicyNumber { get; set; }
public EStatus Status { get; set; }
public virtual List<OpenPosition> OpenPositions { get; set; }
}
public class OpenPosition
{
public int Id { get; set; }
public decimal Amount { get; set; }
[ForeignKey("Mandate")]
public int Mandate_Id { get; set; }
}
**[EDIT] **
For some reasons the [ForeignKey("Mandate")] attribute was removed at compile time (I think it's because the model class is generated. I've found a workaround and the metadata now contains the foreign key MandateId to Mandate in the OpenPositions :
You must define a foreign key as Breeze associations require FKs. http://www.breezejs.com/documentation/navigation-properties
[EDIT]
Your bi-directional association should look like this:
public class Mandate
{
public int Id { get; set; }
public string PolicyNumber { get; set; }
public virtual ICollection<OpenPosition> OpenPositions { get; set; }
}
public class OpenPosition {
public int Id { get; set; }
public decimal Amount { get; set; }
public int MandateId { get; set; }
public Mandate Mandate {get; set; }
}

Categories

Resources