Good day
I'm new to MVC and database relationships.
So i am creating a system of services (product ordering) I understand that there must be a 1: N (One to Many) relationship since a customer can order many products.
I have 2 tables, the first table stores the data of the person requesting the service and the ID generated in this case the name of the variable is REQ_NO, and the second table stores the products requested by the customer.
My problem is the following, How can I assign the ID of the customer that is generated in the database to the products that it asks for, for example: If the customer is generated, ID 304 asks for 2 products, those products are assigned ID 304
NOTE:
TB_CS_TEST2 Is for customer data and req_no
TB_CS_TEST Is for products with req_no assigned form TB_CS_TEST2
Here is my code
Class
public partial class TB_CS_TEST2
{
public decimal REQ_NO { get; set; }
public string REQUESTOR_EMPNO { get; set; }
public string DEPT_CD { get; set; }
public string ORG_NAME { get; set; }
public string EMAIL_ID { get; set; }
public string APPROVER1 { get; set; }
public string APPROVER2 { get; set; }
public Nullable<decimal> TOTAL_AMOUNT { get; set; }
public Nullable<System.DateTime> REQUEST_DATE { get; set; }
public Nullable<System.DateTime> APPROVAL_DATE { get; set; }
public Nullable<System.DateTime> EVENT_DATE { get; set; }
public string EVENT_PLACE { get; set; }
public string PURPOSE { get; set; }
public string REMARKS { get; set; }
public string STATUS { get; set; }
public Nullable<System.DateTime> CRT_DATE { get; set; }
public string EXT { get; set; }
public virtual TB_CS_TEST TB_CS_TEST { get; set; }
}
public partial class TB_CS_TEST
{
public decimal REQ_NO { get; set; }
public Nullable<decimal> SEQ_NO { get; set; }
public Nullable<decimal> ITEM_ID { get; set; }
public Nullable<decimal> QUANTITY { get; set; }
public string UOM { get; set; }
public Nullable<decimal> UNIT_PRICE { get; set; }
public Nullable<decimal> EXTENDED_AMT { get; set; }
public Nullable<System.DateTime> CRT_DATE { get; set; }
public virtual TB_CS_TEST2 TB_CS_TEST2 { get; set; }
}
Controllers
public class DataHeaderController : Controller
{
//
// GET: /DataHeader/
public ActionResult DataHeader()
{
List<MvcApplication31.TB_CS_TEST2> hdr = new List<MvcApplication31.TB_CS_TEST2> { new TB_CS_TEST2 { REQ_NO = 0, REQUESTOR_EMPNO = "", DEPT_CD = "", ORG_NAME = "", EMAIL_ID = "", APPROVER1 = "", APPROVER2 = "", TOTAL_AMOUNT = 0, REQUEST_DATE = DateTime.Now, APPROVAL_DATE = DateTime.Now, EVENT_DATE = DateTime.Now, EVENT_PLACE = "", PURPOSE = "", REMARKS = "", STATUS = "", EXT = "" } };
Entities db = new Entities();
IEnumerable<SelectListItem> listplace = db.TB_RST_SVC_PLACE.Select(c => new SelectListItem
{
Value = c.NAMEPLACE,
Text = c.NAMEPLACE
}
);
// ViewData["NAMEPLACE"] = new SelectList(db.TB_RST_SVC_PLACE, "NAMEPLACE", "NAMEPLACE");
ViewData["NAMEPLACE"] = listplace;
IEnumerable<SelectListItem> listapp = db.TB_RST_SVC_APPROVERS.Select(c => new SelectListItem
{
Value = c.EMAIL_APP,
Text = c.NAME_APP
}
);
ViewData["APPROVER2"] = listapp;
return View(hdr);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult DataHeader(List<MvcApplication31.TB_CS_TEST2> hdr)
{
Entities db = new Entities();
IEnumerable<SelectListItem> listplace = db.TB_RST_SVC_PLACE.Select(c => new SelectListItem
{
Value = c.NAMEPLACE,
Text = c.NAMEPLACE
}
);
// ViewData["NAMEPLACE"] = new SelectList(db.TB_RST_SVC_PLACE, "NAMEPLACE", "NAMEPLACE");
ViewData["NAMEPLACE"] = listplace;
IEnumerable<SelectListItem> listapp = db.TB_RST_SVC_APPROVERS.Select(c => new SelectListItem
{
Value = c.EMAIL_APP,
Text = c.NAME_APP
}
);
ViewData["APPROVER2"] = listapp;
if (ModelState.IsValid)
{
using (Entities cd = new Entities())
{
foreach (var p in hdr)
{
p.CRT_DATE = DateTime.Now;
cd.TB_CS_TEST2.Add(p);
}
cd.SaveChanges();
ModelState.Clear();
hdr = new List<MvcApplication31.TB_CS_TEST2> { new TB_CS_TEST2 { REQ_NO = 0, REQUESTOR_EMPNO = "", DEPT_CD = "", ORG_NAME = "", EMAIL_ID = "", APPROVER1 = "", APPROVER2 = "", TOTAL_AMOUNT = 0, REQUEST_DATE = DateTime.Now, APPROVAL_DATE = DateTime.Now, EVENT_DATE = DateTime.Now, EVENT_PLACE = "", PURPOSE = "", REMARKS = "", STATUS = "", EXT = "" } };
}
}
return View(hdr);
}
}
public class BulkController : Controller
{
//
// GET: /Bulk/
public ActionResult Bulk()
{
//List<MvcApplication31.TB_CS_TEST> ci = new List<MvcApplication31.TB_CS_TEST> { new TB_CS_TEST { REQ = 0, CONTACTNO = "", CONTACTPERSON = "" } };
List<MvcApplication31.TB_CS_TEST> ci = new List<MvcApplication31.TB_CS_TEST> { new TB_CS_TEST { REQ_NO = 0, SEQ_NO = 0, ITEM_ID = 0, QUANTITY = 0, UOM = "", UNIT_PRICE = 0, EXTENDED_AMT = 0 } };
Entities db = new Entities();
IEnumerable<SelectListItem> listplace = db.TB_RST_SVC_PLACE.Select(c => new SelectListItem
{
Value = c.NAMEPLACE,
Text = c.NAMEPLACE
}
);
// ViewData["NAMEPLACE"] = new SelectList(db.TB_RST_SVC_PLACE, "NAMEPLACE", "NAMEPLACE");
ViewData["NAMEPLACE"] = listplace;
IEnumerable<SelectListItem> listapp = db.TB_RST_SVC_APPROVERS.Select(c => new SelectListItem
{
Value = c.EMAIL_APP,
Text = c.NAME_APP
}
);
ViewData["APPROVER2"] = listapp;
IEnumerable<SelectListItem> listproduct = db.TB_POS_PRODUCTS.Select(c => new SelectListItem
{
Value = c.ID.ToString(),
Text = c.DESCRIPTION
}
);
ViewData["PRODUCTS"] = new SelectList(db.TB_POS_PRODUCTS, "ID", "DESCRIPTION");
//ViewData["DESCRIPTION"] = listproduct;
return View(ci);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Bulk(List<MvcApplication31.TB_CS_TEST> ci)
{
Entities db = new Entities();
IEnumerable<SelectListItem> listplace = db.TB_RST_SVC_PLACE.Select(c => new SelectListItem
{
Value = c.NAMEPLACE,
Text = c.NAMEPLACE
}
);
// ViewData["NAMEPLACE"] = new SelectList(db.TB_RST_SVC_PLACE, "NAMEPLACE", "NAMEPLACE");
ViewData["NAMEPLACE"] = listplace;
IEnumerable<SelectListItem> listapp = db.TB_RST_SVC_APPROVERS.Select(c => new SelectListItem
{
Value = c.EMAIL_APP,
Text = c.NAME_APP
}
);
ViewData["APPROVER2"] = listapp;
IEnumerable<SelectListItem> listproduct = db.TB_POS_PRODUCTS.Select(c => new SelectListItem
{
Value = c.ID.ToString(),
Text = c.DESCRIPTION
}
);
ViewData["PRODUCTS"] = new SelectList(db.TB_POS_PRODUCTS, "ID", "DESCRIPTION");
//ViewData["DESCRIPTION"] = listproduct;
if (ModelState.IsValid)
{
using (Entities dc = new Entities())
{
foreach (var i in ci)
{
i.CRT_DATE = DateTime.Now;
dc.TB_CS_TEST.Add(i);
}
dc.SaveChanges();
ViewBag.Message = "Data Successfully saved!";
ModelState.Clear();
//ci = new List<MvcApplication31.TB_CS_TEST> { new MvcApplication31.TB_CS_TEST { CONTACTID = 0, CONTACTNO = "", CONTACTPERSON = "" } };
ci = new List<MvcApplication31.TB_CS_TEST> { new MvcApplication31.TB_CS_TEST { REQ_NO = 0, SEQ_NO = 0, ITEM_ID = 0, QUANTITY = 0, UOM = "", UNIT_PRICE = 0, EXTENDED_AMT = 0 } };
}
}
return View(ci);
}
}
Thanks for your help!
For experience i do the next steps.
if (ModelState.IsValid)
{
using (Entities dc = new Entities())
{
//decimal dcr = dc.TB_CS_TEST2.DefaultIfEmpty().Max(u => u.REQ_NO); THIS CODE PASS DE ID FROM THE OTHER TABLE AND PUT IN A VARIABLE AND USE IN SAVECHANGES
foreach (var i in ci)
{
decimal dcr = dc.TB_CS_TEST2.DefaultIfEmpty().Max(u => u.REQ_NO);
i.REQ_NO = dcr;
i.CRT_DATE = DateTime.Now;
dc.TB_CS_TEST.Add(i);
}
//var cust = new TB_CS_TEST2();
//var pedido = new TB_CS_TEST { TB_CS_TEST2 = cust };
dc.SaveChanges();
SendEmail();
if (dc.SaveChanges() > 0)
{
ViewBag.Message = "Data Successfully saved!";
}
else
{
ViewBag.Message = "Error";
}
ModelState.Clear();
//ci = new List<MvcApplication31.TB_CS_TEST> { new MvcApplication31.TB_CS_TEST { CONTACTID = 0, CONTACTNO = "", CONTACTPERSON = "" } };
ci = new List<MvcApplication31.TB_CS_TEST> { new MvcApplication31.TB_CS_TEST { REQ_NO = 0, SEQ_NO = 0, ITEM_ID = 0, QUANTITY = 0, UOM = "", UNIT_PRICE = 0, EXTENDED_AMT = 0 } };
}
}
return View(ci);
Related
I have 2 models:
public class Office
{
[Key] public int OfficeId { get; set; }
public string Brand { get; set; }
public string Type { get; set; }
[NotMapped] public IRepository<CarItem> CarsDataBase { get; set; }
public virtual ICollection<CarItem> Cars { get; set; }
public Office(string brand, string type)
{
Type = type;
Cars = new List<CarItem>();
Brand = brand;
}
}
and
public class CarItem
{
public CarItem() { } //for serialization
public CarItem(string brand, string model, uint price, uint stockBalance)
{
Brand = brand;
Model = model;
Price = price;
StockBalance = stockBalance;
}
[Key] public int ItemId { get; set; }
public string Brand { get; set; }
public string Model { get; set; }
public uint Price { get; set; }
public uint StockBalance { get; set; }
public int? OfficeId { get; set; }
public Office Office { get; set; }
}
and DataBase Context
public class EFDataBaseContext : DbContext
{
public DbSet<Office> Offices => Set<Office>();
public DbSet<CarItem> CarItems => Set<CarItem>();
public EFDataBaseContext()
{
Database.EnsureCreated();
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlServer("Server=(localdb)\\mssqllocaldb;Database=carstoredb;Trusted_Connection=True;");
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Office>().HasData
(
new Office("Audi", "SQL")
{
OfficeId = 1,
},
new Office("Scoda", "SQL")
{
OfficeId = 2,
}
);
modelBuilder.Entity<CarItem>(entity =>
{
entity.HasOne(item => item.Office).WithMany(office => office.Cars).HasForeignKey(item => item.OfficeId).OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity<SparePart>(entity =>
{
entity.HasOne(item => item.Office).WithMany(office => office.Parts).HasForeignKey(item => item.OfficeId).OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity<CarItem>().HasData
(
new CarItem { OfficeId = 1, ItemId = 1, Brand = "Audi", Model = "A228", Price = 4, StockBalance = 14 },
new CarItem { OfficeId = 1, ItemId = 2, Brand = "Audi", Model = "Super", Price = 44, StockBalance = 5 },
new CarItem { OfficeId = 2, ItemId = 3, Brand = "Scoda", Model = "Logan", Price = 47, StockBalance = 9 },
new CarItem { OfficeId = 2, ItemId = 4, Brand = "Scoda", Model = "Spider", Price = 78, StockBalance = 3 }
);
}
Manually I added an office called BSU.
And in main function I write this:
using (EFDataBaseContext db = new EFDataBaseContext())
{
Office office = mainOffice.Dealerships.FirstOrDefault(of => of.Brand == "BSU");
CarItem carItem = new CarItem(office.Brand, "BSss", 2222, 4);
office.CarsDataBase ??= new EFDataBase(office);
office.CarsDataBase.Create(carItem);
}
Adding a new CarItem to the BSU somehow magically creates a new office named BSU in my database every time a new CarItem is added to the BSU.
using (EFDataBaseContext db = new EFDataBaseContext())
{
Office office = mainOffice.Dealerships.FirstOrDefault(of => of.Brand == "Audi");
CarItem carItem = new CarItem(office.Brand, "AuuuU", 2222, 4);
office.CarsDataBase ??= new EFDataBase(office);
office.CarsDataBase.Create(carItem);
}
Adding a new CarItem to an Audi, on the other hand, does absolutely nothing. No new cars with the Audi brand appear in the database, and nothing at all.
Seems like you're over complicating things
Adding a new Car to an existing Office should perhaps looks like:
var ctx = new EFDatabaseContext();
var off = ctx.Offices.FirstOrDefault(o => o.Type == "Main" and o.Brand == "Audi");
off.Cars.Add(new CarItem(off.Brand, "AuuuU", 2222, 4));
ctx.SaveChanges();
Find the office, add a car, save the changes
This model I would like flat into a view model but the Current Output is not correct it is setting all the ChildProductId to the last value. I am creating one List<SubscriptionViewModel> and then creating multiple SubscriptionViewModel and adding to the collection.
List<Subscription> ListOfSubscriptions = new List<Subscription>();
List<SubscriptionChild> SubscriptionChild = new List<SubscriptionChild>();
SubscriptionChild.Add(new SubscriptionChild() { ChildProductId = 1, ChildProductName = "Child 1" });
SubscriptionChild.Add(new SubscriptionChild() { ChildProductId = 2, ChildProductName = "Child 2" });
ListOfSubscriptions.Add(new Subscription() { SubscriptionId = 1, ParentProductId=1, ParentProductName = "Product 1",ListOfSubscriptionChild= SubscriptionChild });
SubscriptionChild.Clear();
ListOfSubscriptions.Add(new Subscription() { SubscriptionId = 2, ParentProductId = 2, ParentProductName = "Product 2"});
SubscriptionChild.Clear();
SubscriptionChild.Add(new SubscriptionChild() { ChildProductId = 3, ChildProductName = "Child 3" });
SubscriptionChild.Add(new SubscriptionChild() { ChildProductId = 4, ChildProductName = "Child 4" });
ListOfSubscriptions.Add(new Subscription() { SubscriptionId = 3, ParentProductId = 3, ParentProductName = "Product 3", ListOfSubscriptionChild = SubscriptionChild });
List<SubscriptionViewModel> SubscriptionViewModel = new List<SubscriptionViewModel>();
foreach (var Subscription in ListOfSubscriptions)
{
SubscriptionViewModel vm = new SubscriptionViewModel();
vm.SubscriptionId = Subscription.SubscriptionId;
vm.ParentProductId = Subscription.ParentProductId;
vm.ParentProductName = Subscription.ParentProductName;
int count = Subscription.ListOfSubscriptionChild == null ? 0 : Subscription.ListOfSubscriptionChild.Count;
if (count == 0) {
SubscriptionViewModel.Add(vm);
}
else
{
var listOfChild = Subscription.ListOfSubscriptionChild.ToList();
foreach (var item in listOfChild)
{
vm.ChildProductId = item.ChildProductId;
vm.ChildProductName = item.ChildProductName;
SubscriptionViewModel.Add(vm);
}
}
}
foreach (var item in SubscriptionViewModel)
{
Console.WriteLine(string.Format("SubscriptionId{0} ParentProductId-{1} ChildProductId-{2}", item.SubscriptionId, item.ParentProductId, item.ChildProductId));
}
class Subscription
{
public int SubscriptionId { get; set; }
public int ParentProductId { get; set; }
public string ParentProductName { get; set; }
public List<SubscriptionChild> ListOfSubscriptionChild { get; set; }
}
class SubscriptionChild
{
public string ChildProductName { get; set; }
public int ChildProductId { get; set; }
}
class SubscriptionViewModel
{
public int SubscriptionId { get; set; }
public int ParentProductId { get; set; }
public string ParentProductName { get; set; }
public string ChildProductName { get; set; }
public int ChildProductId { get; set; }
}
Current Output
SubscriptionId1 ParentProductId-1 ChildProductId-4
SubscriptionId1 ParentProductId-1 ChildProductId-4
SubscriptionId2 ParentProductId-2 ChildProductId-0
SubscriptionId3 ParentProductId-3 ChildProductId-4
SubscriptionId3 ParentProductId-3 ChildProductId-4
expected outcome
SubscriptionId1 ParentProductId-1 ChildProductId-1
SubscriptionId1 ParentProductId-1 ChildProductId-2
SubscriptionId2 ParentProductId-2 ChildProductId-0
SubscriptionId3 ParentProductId-3 ChildProductId-3
SubscriptionId3 ParentProductId-3 ChildProductId-4
You're overwriting your SubscriptionViewModel for all of your children. You need to create a new one for each child:
foreach (var Subscription in ListOfSubscriptions)
{
int count = Subscription.ListOfSubscriptionChild == null ? 0 : Subscription.ListOfSubscriptionChild.Count;
if (count == 0)
{
SubscriptionViewModel vm = new SubscriptionViewModel();
vm.SubscriptionId = Subscription.SubscriptionId;
vm.ParentProductId = Subscription.ParentProductId;
vm.ParentProductName = Subscription.ParentProductName;
SubscriptionViewModel.Add(vm);
}
else
{
var listOfChild = Subscription.ListOfSubscriptionChild.ToList();
foreach (var item in listOfChild)
{
// Instantiate a new model for each child
SubscriptionViewModel vm = new SubscriptionViewModel();
vm.SubscriptionId = Subscription.SubscriptionId;
vm.ParentProductId = Subscription.ParentProductId;
vm.ParentProductName = Subscription.ParentProductName;
vm.ChildProductId = item.ChildProductId;
vm.ChildProductName = item.ChildProductName;
SubscriptionViewModel.Add(vm);
}
}
}
I am using Pagedlist for Pagination in my MVC project. Pagination is working for most of the cases without ViewModels.
But when I use a ViewModel PagedList generating Pagination links but without any parameter value to querystring page.
Here is my ViewModel
public class SearchResult
{
public int ItemID { get; set; }
public string ItemTitle { get; set; }
public int? AuthorID { get; set; }
public string AuthorName { get; set; }
public int? IssueDate { get; set; }
}
And ActionResult Method
public ActionResult Date(int? page)
{
try
{
string query;
if (Request.RequestContext.RouteData.Values["query"] != null)
{
using (dreposEntities db = new dreposEntities())
{
query = Request.RequestContext.RouteData.Values["query"].ToString();
int issueYear = int.Parse(query);
ViewBag.Query = issueYear;
var dateFilter = db.itemstreams.Where(q => q.issuedate == issueYear).ToList();
List<SearchResult> resultList = new List<SearchResult>();
if (dateFilter.Any())
{
foreach (var c in dateFilter)
{
SearchResult obj = new SearchResult
{
ItemID = c.id,
ItemTitle = c.title,
IssueDate = c.issuedate,
};
resultList.Add(obj);
}
}
ViewBag.SearchQuery = query;
return View(resultList.OrderBy(d=>d.IssueDate).ToPagedList(page ?? 1, 10));
}
}
else
{
using (dreposEntities db = new dreposEntities())
{
List<SearchResult> resultList = new List<SearchResult>();
var files = db.itemstreams.Where(s=>s.status==1).ToList();
if (files.Any())
{
foreach (var f in files)
{
SearchResult obj = new SearchResult
{
ItemID = f.id,
ItemTitle = f.title,
IssueDate = f.issuedate,
};
resultList.Add(obj);
}
}
return View(resultList.OrderBy(d=>d.IssueDate).ToPagedList(page ?? 1, 10));
}
}
}
catch (Exception e)
{
return View();
}
}
What above code is showing in View is attached in below email
And in View/Razor
<div class="pull-right">
#Html.PagedListPager(Model, page => Url.Action("Date", new { page }), new PagedListRenderOptions() { Display = PagedListDisplayMode.IfNeeded })
</div>
This question already has answers here:
How to Sort a List<T> by a property in the object
(23 answers)
Closed 4 years ago.
I have the following classes.
public class Response
{
List<Make> Makes { get; set; }
public Response()
{
this.Makes = new List<Make>();
}
}
public class Make
{
public string Name { get; set; }
public List<Agent> Agents { get; set; }
public Make()
{
this.Agents = new List<Agent>();
}
}
public class Agent
{
public int Id { get; set; }
public string Name { get; set; }
public List<Offer> Offers { get; set; }
public Agent()
{
this.Offers = new List<Offer>();
}
}
public class Offer
{
public int Id { get; set; }
public List<Model> Models { get; set; }
public Offer()
{
this.Models = new List<Model>();
}
}
public class Model
{
public string Name { get; set; }
public Price Price { get; set; }
public Model()
{
this.Price = new Price();
}
}
public class Price
{
public decimal Total { get; set; }
public decimal Vat { get; set; }
}
Using linq how can I get a list of Makes, that are ordered by the cheapest model first. Also, I want the models for each agent to be ordered by the cheapest first.
The easy way is to put the data into a flat object like a datatable and then sort :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
namespace ConsoleApplication98
{
class Program
{
static void Main(string[] args)
{
Response response = new Response() {
Makes = new List<Make>() {
new Make() {
Name = "AAA", Agents = new List<Agent>() {
new Agent() {
Id = 123, Name = "SSS", Offers = new List<Offer>() {
new Offer() {
Id = 100, Models = new List<Model>() {
new Model() { Name = "TTT", Price = new Price() { Total = 1.0M, Vat = 2.0M}},
new Model() { Name = "UUU", Price = new Price() { Total = 2.0M, Vat = 3.0M}},
},
},
new Offer() {
Id = 200, Models = new List<Model>() {
new Model() { Name = "TTT", Price = new Price() { Total = 1.0M, Vat = 2.0M}},
new Model() { Name = "UUU", Price = new Price() { Total = 2.0M, Vat = 3.0M}}
}
}
}
},
new Agent() {
Id = 456, Name = "SST", Offers = new List<Offer>() {
new Offer() {
Id = 100, Models = new List<Model>() {
new Model() { Name = "TTT", Price = new Price() { Total = 1.0M, Vat = 2.0M}},
new Model() { Name = "UUU", Price = new Price() { Total = 2.0M, Vat = 3.0M}},
},
},
new Offer() {
Id = 200, Models = new List<Model>() {
new Model() { Name = "TTT", Price = new Price() { Total = 1.0M, Vat = 2.0M}},
new Model() { Name = "UUU", Price = new Price() { Total = 2.0M, Vat = 3.0M}}
}
}
}
}
}
},
new Make() {
Name = "AAB", Agents = new List<Agent>() {
new Agent() {
Id = 123, Name = "SSS", Offers = new List<Offer>() {
new Offer() {
Id = 100, Models = new List<Model>() {
new Model() { Name = "TTT", Price = new Price() { Total = 1.0M, Vat = 2.0M}},
new Model() { Name = "UUU", Price = new Price() { Total = 2.0M, Vat = 3.0M}},
},
},
new Offer() {
Id = 200, Models = new List<Model>() {
new Model() { Name = "TTT", Price = new Price() { Total = 1.0M, Vat = 2.0M}},
new Model() { Name = "UUU", Price = new Price() { Total = 2.0M, Vat = 3.0M}}
}
}
}
},
new Agent() {
Id = 456, Name = "SST", Offers = new List<Offer>() {
new Offer() {
Id = 100, Models = new List<Model>() {
new Model() { Name = "TTT", Price = new Price() { Total = 1.0M, Vat = 2.0M}},
new Model() { Name = "UUU", Price = new Price() { Total = 2.0M, Vat = 3.0M}},
},
},
new Offer() {
Id = 200, Models = new List<Model>() {
new Model() { Name = "TTT", Price = new Price() { Total = 1.0M, Vat = 2.0M}},
new Model() { Name = "UUU", Price = new Price() { Total = 2.0M, Vat = 3.0M}}
}
}
}
}
}
}
}
};
DataTable dt = new DataTable();
dt.Columns.Add("Make Name", typeof(string));
dt.Columns.Add("Agent ID", typeof(int));
dt.Columns.Add("Agent Name", typeof(string));
dt.Columns.Add("Offer ID", typeof(int));
dt.Columns.Add("Model Name", typeof(string));
dt.Columns.Add("Total", typeof(decimal));
dt.Columns.Add("Vat", typeof(decimal));
foreach (Make make in response.Makes)
{
string makeName = make.Name;
foreach (Agent agent in make.Agents)
{
int agentID = agent.Id;
string agentName = agent.Name;
foreach (Offer offer in agent.Offers)
{
int offerID = offer.Id;
foreach (Model model in offer.Models)
{
string modelName = model.Name;
decimal vat = model.Price.Vat;
decimal total = model.Price.Total;
dt.Rows.Add(new object[] {
makeName,
agentID,
agentName,
offerID,
modelName,
vat,
total
});
}
}
}
}
dt = dt.AsEnumerable().OrderBy(x => x.Field<decimal>("Total")).CopyToDataTable();
}
}
public class Response
{
public List<Make> Makes { get; set; }
public Response()
{
this.Makes = new List<Make>();
}
}
public class Make
{
public string Name { get; set; }
public List<Agent> Agents { get; set; }
public Make()
{
this.Agents = new List<Agent>();
}
}
public class Agent
{
public int Id { get; set; }
public string Name { get; set; }
public List<Offer> Offers { get; set; }
public Agent()
{
this.Offers = new List<Offer>();
}
}
public class Offer
{
public int Id { get; set; }
public List<Model> Models { get; set; }
public Offer()
{
this.Models = new List<Model>();
}
}
public class Model
{
public string Name { get; set; }
public Price Price { get; set; }
public Model()
{
this.Price = new Price();
}
}
public class Price
{
public decimal Total { get; set; }
public decimal Vat { get; set; }
}
}
It would be easier to verify if you'd provided sample values and the desired result, but here's my take on getting the Makes ordered using a LINQ one-liner:
response.Makes.OrderBy(
make => make.Agents.Select(
agent => agent.Offers.Min(
offer => offer.Models.OrderBy(model => model.Price.Total)
.First().Price.Total)));
Here's the flow (the inner bullets enable the outer bullets):
Get list of Makes
For each Make, select list of Agents
For each Agent, select the minimum offer
For each offer, order by the total price
Select the first (lowest) offer
For each Agent, the minimum offer is now selected
The makes can now be ordered by the minimum offer it contains
I'm not absolutely certain that the flow above makes sense, but give the implementation a shot!
im trying pass a object since View to controller as ViewModel. But some arrive field empty to controller. This fields are KeyValuePair and have not idea for pass it correctly to Controller.
This is my code:
Controller:
public ActionResult Index(SearchResultsViewModel searchResultsViewModel)
{
PassengerDataViewModel viewModel = new PassengerDataViewModel()
{
Request = searchResultsViewModel,
PassengerType = GetPassengerTypes(),
NumberPeople = GetNumberPeople()
};
return View("PassengerData", viewModel);
}
ViewModel:
public class SearchResultsViewModel
{
public SearchViewModel Request { get; set; }
public string SearchFlightDatesText { get; set; }
public string SearchPaxSelectionText { get; set; }
public KeyValuePair<string, string> DepartureStation { get; set; }
public KeyValuePair<string, string> ArrivalStation { get; set; }
public DateTime BeginDate { get; set; }
public DateTime EndDate { get; set; }
public DateTime SelectedDate { get; set; }
public int SelectedDay { get; set; }
public List<FlightsResponseDTO> Days { get; set; }
public KeyValuePair<string, string> DepartureStation2 { get; set; }
public KeyValuePair<string, string> ArrivalStation2 { get; set; }
public List<FlightsResponseDTO> Days2 { get; set; }
public DateTime BeginDate2 { get; set; }
public DateTime EndDate2 { get; set; }
public DateTime SelectedDate2 { get; set; }
public int SelectedDay2 { get; set; }
}
View Code
Post = function (path, params, method) {
method = method || "post"; // Set method to post by default if not specified.
// The rest of this code assumes you are not using a library.
// It can be made less wordy if you use one.
var form = document.createElement("form");
form.setAttribute("method", method);
form.setAttribute("action", path);
debugger;
for (var key in params) {
if (params.hasOwnProperty(key)) {
var hiddenField = document.createElement("input");
hiddenField.setAttribute("type", "hidden");
hiddenField.setAttribute("name", key);
hiddenField.setAttribute("value", params[key]);
form.appendChild(hiddenField);
}
}
debugger;
document.body.appendChild(form);
form.submit();
}
$("a.baseButton.yellowButton.mediumButton").click(function (event) {
//Comprobamos si esta seleccionado un vuelo
if(!checkIfFlightSelected()){
$('#error-dialog').dialog({
modal: true,
height: 130,
width: 360
});
event.preventDefault();
return false;
}
//--------------Inicio SearchViewModel ------------------------------
debugger;
var departureStation = "#Model.Request.SelectedOrigin1";
var arrivalStation = "#Model.Request.SelectedDestination1";
var departureDate = "#Model.Request.SelectedFlightDate1";
var departureStation2 = "#Model.Request.SelectedOrigin2";
var arrivalStation2 = "#Model.Request.SelectedDestination2";
var departureDate2 = "#Model.Request.SelectedFlightDate2";
var adults = "#Model.Request.NumAdults";
var childs = "#Model.Request.NumChilds";
var infants = "#Model.Request.NumInfants";
var residentOrFamily ="#Model.Request.SelectedResidentOrLargueFamilyDiscount";
var PassengersWithDiscount = "#Model.Request.NumPassengersWithSpecialDiscount";
var tipo = "#Model.Request.SelectedSearchType";
var searchViewModelRequest = {
SelectedSearchType: tipo,
SelectedOrigin1: departureStation,
SelectedDestination1: arrivalStation,
SelectedFlightDate1: departureDate,
Tipo:tipo,
//SelectedOrigin2: departureStation2,
//SelectedDestination2: arrivalStation2,
//SelectedFlightDate2: departureDate2,
NumAdults: adults,
NumChilds: childs,
NumInfants: infants,
SelectedResidentOrLargueFamilyDiscount: residentOrFamily,
NumPassengersWithSpecialDiscount: PassengersWithDiscount
};
//-------------------Fin SearchViewModel---------------------------------
//Inicio SearchResultsViewModel
//-----------Datos para obtenr datos seleccioandos------------------
var partsId = $("#availabilityTable0 :input:checked")[0].id.split('_');
var day = calendariCarregat.Days[partsId[1]];
var journey=day.Journeys[partsId[2]];
var departureDate = new Date(journey.JourneySellKey.split('~')[5].split(' ')[0]);
//var arrivalDate = new Date(journey.JourneySellKey.split('~')[7].split(' ')[0]);
var departureHourDate = journey.DepartureTimeString;
var arrivalHourDate = journey.ArrivalTimeString;
var departureDay;
var departureMonth;
if (departureDate.getUTCDate() + 1 < 10) {
departureDay = "0" + (departureDate.getUTCDate() + 1);
} else {
departureDay = (departureDate.getUTCDate() + 1);
}
if (departureDate.getUTCDate() + 1 < 10) {
departureMonth = "0" + (departureDate.getUTCMonth() + 1);
} else {
departureMonth = (departureDate.getUTCMonth() + 1);
}
var normalDepartureDate = (departureDay) + "/" + (departureMonth) + "/" + departureDate.getUTCFullYear();
//----------------------Fin datos seleccionados--------------
var searchFlightDatesText = "#Model.SearchFlightDatesText";
var searchPaxSelectionText = "#Model.SearchPaxSelectionText";
var departureStation = {
"Key": "#Model.DepartureStation.Key",
"Value": "#Model.DepartureStation.Value"
};
var arrivalStation = {
"Key": "#Model.ArrivalStation.Key",
"Value": "#Model.ArrivalStation.Value"
};
var beginDate = "#Model.BeginDate";
var endDate = "#Model.EndDate";
var selectedDate = normalDepartureDate;
var selectedDay = "#Model.SelectedDay";
var days = "#Model.Days";
//var departureStation2 = null;
//var arrivalStation2 = null;
//var days2 = null;
//var beginDate2 = null;
//var endDate2 = null;
//var selectedDate2 = null;
//var selectedDay2 = null;
var searchResultsViewModel = {
//Request: searchViewModelRequest.toString(),
"Request.SelectedOrigin1": searchViewModelRequest.SelectedOrigin1,
"Request.SelectedSearchType": searchViewModelRequest.Tipo,
"Request.SelectedDestination1": searchViewModelRequest.SelectedDestination1,
"Request.SelectedFlightDate1": searchViewModelRequest.SelectedFlightDate1,
"Request.NumAdults": searchViewModelRequest.NumAdults,
"Request.NumChilds": searchViewModelRequest.NumChilds,
"Request.NumInfants": searchViewModelRequest.NumInfants,
"Request.IncrementSelectedFlightDate1": 0,
"Request.SelectedResidentOrLargueFamilyDiscount": searchViewModelRequest.SelectedResidentOrLargueFamilyDiscount,
"Request.NumPassengersWithSpecialDiscount": searchViewModelRequest.NumPassengersWithSpecialDiscount,
SearchFlightDatesText: searchFlightDatesText,
SearchPaxSelectionText: searchPaxSelectionText,
"DepartureStation.Key": "test",
"DepartureStation.Value": "test",
"ArrivalStation": "{ [test, test]}",
BeginDate: beginDate,
EndDate: endDate,
SelectedDate: selectedDate,
SelectedDay: selectedDay,
Days: days,
"DepartureStation2.Key": "test",
"DepartureStation2.Value": "test",
};
//--------------Fin SearchResultsViewModel
MICESearcher.Post('#Url.Action("Index", "PassengerData")', (searchResultsViewModel));
});
i have tried it pass values of many ways to the KeyValuePair but i could not achieve it
Edit(solved):
finally thanks to #Daniel J.G, I could solve the problem by following this website ASP MVC.NET - how to bind KeyValuePair?
thank you all for the help!!