Bind IEnumerable to ViewModel in C# MVC - c#

I have a table in my view that a model is typed to it. However, now I need to change that model to a ViewModel (so I can Union other models on to it but one step at a time). Currently, I query my model (which works) but now I need to figure out how to convert that IEnumerable to bind it to the ViewModel (in this case, it is searchResultViewModel). I gathered what i would need to loop through each line in the IEnumerable and bind it individually (that is what the foreach loop is, me trying that) but I need to convert it back in to an 'IEnumerable'. How do I bind the IEnumerable to my ViewModel but as an 'IEnumerable'? I cannot find anyone else asking a question like this.
[HttpPost]
public ActionResult SearchResult(SearchOrders searchOrders)
{
var orderList = uni.Orders;
var model = from order in orderList
select order;
if (searchOrders.SearchStartDate.HasValue)
{
model = model.Where(o => o.OrderDate >= searchOrders.SearchStartDate);
}
if (searchOrders.SearchEndDate.HasValue)
{
model = model.Where(o => o.OrderDate <= searchOrders.SearchEndDate);
}
if (searchOrders.SearchAmount.HasValue)
{
model = model.Where(o => o.Total == searchOrders.SearchAmount);
}
var searchResultViewModel = new SearchResultViewModel();
foreach (var record in model)
{
searchResultViewModel.OrderNumber = record.OrderId;
searchResultViewModel.PaymentName = record.PaymentFullName;
searchResultViewModel.OrderDate = record.OrderDate;
searchResultViewModel.Amount = record.Total;
}
return View(model);
}
Here is my SearchOrders Model:
namespace MicrositeInfo.WebUI.Models
{
public class SearchOrders
{
public DateTime? SearchStartDate { get; set; }
public DateTime? SearchEndDate { get; set; }
public decimal? SearchAmount { get; set; }
}
}
and here is my SearchResultViewModel:
namespace MicrositeInfo.WebUI.Models
{
public class SearchResultViewModel
{
public int OrderNumber { get; set; }
public string PaymentName { get; set; }
public DateTime OrderDate { get; set; }
public decimal Amount { get; set; }
}
}
and the model that is being queried is the order model:
namespace MicrositeInfo.Model
{
[Table("Order")]
public class Order
{
public int OrderId { get; set; }
public string SelectedSession { get; set; }
public string StudentCity { get; set; }
public string StudentExtension { get; set; }
public string StudentFullName { get; set; }
public string StudentPhone { get; set; }
public string StudentPin { get; set; }
public string StudentState { get; set; }
public string StudentStreet01 { get; set; }
public string StudentStreet02 { get; set; }
public string StudentUniversityId { get; set; }
public string StudentZip { get; set; }
public string PaymentCity { get; set; }
public string PaymentCreditCardExpiration { get; set; }
public string PaymentCreditCardNumber { get; set; }
public string PaymentCreditCardSecurityCode { get; set; }
[Display(Name="Payment Name")]
public string PaymentFullName { get; set; }
public string PaymentState { get; set; }
public string PaymentStreet01 { get; set; }
public string PaymentStreet02 { get; set; }
public string PaymentZip { get; set; }
[Display(Name = "Package Id")]
[ForeignKey("Product")]
public int ProductId { get; set; }
public virtual Product Product { get; set; }
public decimal Price { get; set; }
public decimal Tax { get; set; }
public decimal Total { get; set; }
[Display(Name = "Order Date")]
public DateTime OrderDate { get; set; }
public string OrderIp { get; set; }
public string StudentEmail { get; set; }
public string PaymentId { get; set; }
public int Status { get; set; }
public string ApprovalCode { get; set; }
public decimal Shipping { get; set; }
public string STCITrackingClassCode { get; set; }
}
}

Related

Deserializing JSON object says Input string is not a valid integer

i have this Json
{
"queryresult":{
"responseMessage":"success",
"customer":{
"accountNumber":"8292829222",
"meterNumber":"",
"phoneNumber":"",
"lastName":"CHRISTIAN ",
"address":"2 OSISIOMA NGWA, ABIA",
"city":null,
"district":"Damata",
"userCategory":"NON-MD",
"customerType":"unmetered",
"paymentPlan":"Postpaid",
"vat":463.8525,
"tariffCode":"R2SC-NMD",
"tariffRate":53.78,
"arrearsBalance":129324.8435,
"billedAmount":6184.7,
"billedDate":"08-2022",
"lastPayDate":null,
"lastpayment":{
}
},
"responseCode":200,
"status":"true"
},
"status":true
}
When i deserialize with
var data = JsonConvert.DeserializeObject<Data>(readTask);
it throws and error saying
Input String '463.8525' is not a valid integer
which is the vat field
How do i solve this issue? below is my model
public class customer
{
public string accountNumber { get; set; }
public string meterNumber { get; set; }
public string phoneNumber { get; set; }
public string lastName { get; set; }
public string address { get; set; }
public object city { get; set; }
public string district { get; set; }
public string userCategory { get; set; }
public string customerType { get; set; }
public string paymentPlan { get; set; }
public double vat { get; set; }
public string tariffCode { get; set; }
public double tariffRate { get; set; }
public double? arrearsBalance { get; set; }
public double billedAmount { get; set; }
public string? billedDate { get; set; }
public string? lastPayDate { get; set; }
public Lastpayments lastpayment { get; set; }
}
public class Lastpayments
{
public string transactionRef { get; set; }
public int units { get; set; }
public string transactionDate { get; set; }
public string transactionId { get; set; }
public int transactionBookId { get; set; }
public int? amountPaid { get; set; }
public int mscPaid { get; set; }
public string invoiceNumber { get; set; }
}
public class Queryresults
{
public string responseMessage { get; set; }
public customer customer { get; set; }
public int responseCode { get; set; }
public string status { get; set; }
}
public class Data
{
public Queryresults queryresult { get; set; }
public bool status { get; set; }
}
The error points to the vat field. I tried using [JsonIgnore] to Ignore the vat field as i dont really need it but it dint work

Accessing Nested Collection View JSON data

I have a nested JSON data to be accessed. The data is structured into nested data which i want to have into one.
I modeled the JSON response into c# model classes
public class Customer1
{
public string district { get; set; }
public string feeder { get; set; }
public string feeder_code { get; set; }
public string transformer { get; set; }
public string dss_code { get; set; }
public string database_match { get; set; }
public string accountnumber { get; set; }
public string meterno { get; set; }
public TransactionalDetails transactional_details { get; set; }
}
public class Customer2
{
public string accountNumber { get; set; }
public string meterNumber { get; set; }
public string phoneNumber { get; set; }
public int billedAmount { get; set; }
public object billedDate { get; set; }
public string lastPayDate { get; set; }
public Lastpayment lastpayment { get; set; }
}
public class Lastpayment
{
public string transactionRef { get; set; }
public int units { get; set; }
public string transactionDate { get; set; }
public string transactionId { get; set; }
public int transactionBookId { get; set; }
public int amountPaid { get; set; }
public int mscPaid { get; set; }
public string invoiceNumber { get; set; }
}
public class Queryresult
{
public string responseMessage { get; set; }
public Customer1 customer1 { get; set; }
public int responseCode { get; set; }
public string status { get; set; }
}
public class Result
{
public ObservableCollection<Customer1> Customer1 { get; set; }
public int row_count { get; set; }
}
public class Root
{
public bool error { get; set; }
public Result result { get; set; }
}
public class TransactionalDetails
{
public Queryresult queryresult { get; set; }
public bool status { get; set; }
}
I also created the following code to access the data using the root.
var data = JsonConvert.DeserializeObject<root>(readTask);
ObservableCollection<Customer1> innerData2 = data.result.Customer1;
My challenge is that i want to have Customer1, Customer2 and last payment data merged into a single collection view.
with what i have done, i can only access customer1 data. how can i access all into a single collection?

E.F Core does not return all values When Include another table

public IEnumerable<Parties> GetAll()
{
return database.Parties;
}
Works very well and the output is:
But when I Include another table by foreignkey like this:
public IEnumerable<Parties> GetAll()
{
return database.Parties.Include(i=>i.User);
}
It does not work, it returns first value of the table and nothing else,the output is :
Users.cs :
public partial class Users
{
public Users()
{
Parties = new HashSet<Parties>();
PartyParticipants = new HashSet<PartyParticipants>();
}
public int Id { get; set; }
public string Name { get; set; }
public string Surname { get; set; }
public string Username { get; set; }
public string Email { get; set; }
public string Avatar { get; set; }
public string Biography { get; set; }
public string Password { get; set; }
public virtual ICollection<Parties> Parties { get; set; }
public virtual ICollection<PartyParticipants> PartyParticipants { get; set; }
}
Parties.cs :
public partial class Parties
{
public Parties()
{
Image = new HashSet<Image>();
PartyParticipants = new HashSet<PartyParticipants>();
}
public int Id { get; set; }
public string Name { get; set; }
public DateTime PartyDate { get; set; }
public DateTime CreatedDate { get; set; }
public int ParticipantCount { get; set; }
public int MaxParticipant { get; set; }
public string PartySplash { get; set; }
public string ShortDescription { get; set; }
public string Description { get; set; }
public double Latitude { get; set; }
public double Longitude { get; set; }
public bool EntranceFree { get; set; }
public int? FreeParticipant { get; set; }
public int? FreeParticipantMax { get; set; }
public int UserId { get; set; }
public virtual Users User { get; set; }
public virtual ICollection<Image> Image { get; set; }
public virtual ICollection<PartyParticipants> PartyParticipants { get; set; }
}
As you can see on the 2nd picture it interrupts at first row of the table.
I have added this answer based on Vidmantas's comment. ReferenceLoopHandling should be ignored like this in startup.cs:
services.AddMvc()
.AddJsonOptions(options =>
{
options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
});

LINQ: Group by and Join

I have 2 models:
public partial class Movie
{
public Movie()
{
TimeTables = new HashSet<TimeTable>();
}
[Key]
public int MovieId { get; set; }
public string MovieName { get; set; }
public int MovieGenre { get; set; }
public string MoviePicture { get; set; }
public string MovieDescription { get; set; }
public string MovieShortText { get; set; }
public bool? MovieIs3d { get; set; }
public bool? MovieIsImax { get; set; }
public int MovieLanguage { get; set; }
public bool? MovieSubtitled { get; set; }
public int? MovieMinimalAge { get; set; }
public bool? MovieHasDrugs { get; set; }
public bool? MovieHasViolence { get; set; }
public bool? MovieHasSex { get; set; }
public bool? MovieHasSwearing { get; set; }
public bool? MovieIsScary { get; set; }
public bool? MovieHasDiscrimination { get; set; }
public string MovieTrailer { get; set; }
public int MovieLength { get; set; }
public int? Genre_GenreId { get; set; }
public int? Language_LanguageId { get; set; }
public virtual Genre Genre { get; set; }
public virtual Language Language { get; set; }
public virtual ICollection<TimeTable> TimeTables { get; set; }
}
And:
public partial class TimeTable
{
public TimeTable()
{
Reservations = new HashSet<Reservation>();
}
public int TimeTableId { get; set; }
public int MovieId { get; set; }
public int RoomId { get; set; }
public int SeatsAvaible { get; set; }
public DateTime StartTime { get; set; }
public DateTime EndTime { get; set; }
public virtual Movie Movie { get; set; }
public virtual ICollection<Reservation> Reservations { get; set; }
public virtual Room Room { get; set; }
}
I want to show all the records from Movie which have one or more records in TimeTable and where StartDate.date == [given datetime].
With a simple query the movies are showing multiple times. I have tried a distinct() but that changes nothing.
Anybody here who have the solution?
Current query:
var times2 =
(from s in timetablerepo.TimeTables
orderby s.StartTime.TimeOfDay
where s.StartTime.Date == datetime.Date
select s).Distinct().ToList();
Why not start with movies first and filter by timetable:
var times = timetablerepo.Movies
.Where(m => m.TimeTables.Any(t => t.StartDate.Date == <yourdate>));

How to search a head then save a new member under that head in asp.net mvc 5?

i have this screen shot of my project on desktop application but now i want to do it on my asp.net mvc 5 application. Please see the picture shown below:
Members
public partial class Member
{
public Member()
{
this.Acc_Transactions = new HashSet<Acc_Transactions>();
this.Addresses12 = new HashSet<Addresses1>();
this.BankingDetails = new HashSet<BankingDetail>();
this.Contacts = new HashSet<Contact>();
this.TalentCommitments = new HashSet<TalentCommitment>();
this.Pledges = new HashSet<Pledge>();
}
public int m_id { get; set; }
public int title_id { get; set; }
public string initial { get; set; }
public string fname { get; set; }
public string lname { get; set; }
public Nullable<System.DateTime> dob { get; set; }
public string maritial { get; set; }
public string religion { get; set; }
public string occupation { get; set; }
public string company { get; set; }
public string Note { get; set; }
public Nullable<int> Memtype_Id { get; set; }
public string employed { get; set; }
public Nullable<System.DateTime> reg_date { get; set; }
public string AccNumb { get; set; }
public string Hnumber { get; set; }
public Nullable<bool> Active { get; set; }
public string AgeGrp { get; set; }
public int h_id { get; set; }
public Nullable<int> postal_addid { get; set; }
public Nullable<int> phys_addid { get; set; }
public Nullable<int> maritialid { get; set; }
public Nullable<bool> PlndGv { get; set; }
public virtual ICollection<Acc_Transactions> Acc_Transactions { get; set; }
public virtual Addresses1 Addresses1 { get; set; }
public virtual Addresses1 Addresses11 { get; set; }
public virtual ICollection<Addresses1> Addresses12 { get; set; }
public virtual ICollection<BankingDetail> BankingDetails { get; set; }
public virtual ICollection<Contact> Contacts { get; set; }
public virtual Head Head { get; set; }
public virtual Maritial Maritial1 { get; set; }
public virtual ICollection<TalentCommitment> TalentCommitments { get; set; }
public virtual MemberType MemberType { get; set; }
public virtual ICollection<Pledge> Pledges { get; set; }
public virtual Title Title { get; set; }
}
}
Heads
public partial class Head
{
public Head()
{
this.Addresses1 = new HashSet<Addresses1>();
this.Members = new HashSet<Member>();
}
public int h_id { get; set; }
public string h_initials { get; set; }
public string fname { get; set; }
public string lname { get; set; }
public string Email { get; set; }
public string cell { get; set; }
public string cell2 { get; set; }
public string tel_h { get; set; }
public string tel_w { get; set; }
public string fax { get; set; }
public string h_no { get; set; }
public int title_id { get; set; }
public Nullable<bool> active { get; set; }
public virtual ICollection<Addresses1> Addresses1 { get; set; }
public virtual ICollection<Member> Members { get; set; }
public virtual Title Title { get; set; }
}
ViewModel
public class MembersViewModel
{
public int m_id { get; set; }
public string titles { get; set; }
public string initial { get; set; }
public string fname{ get; set; }
public string lname { get; set; }
public string email { get; set; }
public Nullable<System.DateTime> dob { get; set; }
public string maritials { get; set; }
public string religion { get; set; }
public string occupation { get; set; }
public string company { get; set; }
public string note { get; set; }
public string employed { get; set; }
public Nullable<System.DateTime> regdate { get; set; }
public string accNumb { get; set; }
public string hnumber { get; set; }
public string agegroup { get; set; }
public string plandGv { get; set; }
public string cell { get; set; }
public string tel_h { get; set; }
public int title_id { get; set; }
public string flatName { get; set; }
public string flatNo { get; set; }
public string strname { get; set; }
public string strNo { get; set; }
public string suburb { get; set; }
public string city { get; set; }
public string tel_w { get; set; }
public string fax { get; set; }
public string cell2 { get; set; }
public bool active { get; set; }
public string province { get; set; }
public string country { get; set; }
public int? postalcode { get; set; }
public string zone { get; set; }
public bool isHa { get; set; }
public int addtype { get; set; }
public int PhysAddID { get; set; }
public Nullable<int> phys_addid { get; set; }
public int h_id { get; set; }
public int maritialid { get; set; }
public int Memtype_Id { get; set; }
}
}
Index Action:
public ActionResult Index()
{
HeadVM list = new HeadVM()
{
data = new List<Heads>()
};
var AllHeads = db.Heads;
foreach (var item in AllHeads)
{
if (item != null)
{
list.data.Add(new Heads
{
h_id = item.h_id,
fname = item.fname,
lname = item.lname,
});
}
}
return View(list);
}
My problem is that I want to first search heads details, then after i searched the heads details when i click a particular head it must only display the h_id not all details then i save a new member under that H_id. Please help.
Lets start with an initial view we will call Index. So we will need a ViewModel for it, lets call it HeadVM
[Serializable]
public class HeadVM
{
public List<Heads> data { get; set; }
}
public class Heads
{
public int h_id { get; set; }
public string fname { get; set; }
public string lname { get; set; }
}
I am assuming we will just be populating the entire initial view with a complete list of all the heads.
Now for our action:
public ActionResult Index()
{
HeadVM list = new HeadVM()
{
data = new List<Heads>()
};
var AllHeads = context.Heads;
foreach (var item in AllHeads)
{
if (item != null)
{
list.data.Add(new Heads
{
h_id = item.h_id,
fname = item.fname,
lname = item.lname,
});
}
}
return View(list);
}
This will return a list of Heads to your Index view, where you can simply show and access each Head with a button. In this case I use a table as I find it is the simplest to display a list:
#model ...HeadVM
<table border="1">
<tr>
<th>HeaderID</th>
<th>First Name</th>
<th>Last Name</th>
<td></td>
</tr>
#foreach(var item in Model.data)
<tr>
<td>#item.h_id</td>
<td>#item.fname</td>
<td>#item.lname</td>
<td>#Html.ActionLink("Add Member", "Create", "Home", new { id = item.h_id }, new { target = "_blank" })</td>
</tr>
This will give a list of heads, with a button in each row "Add member"(As I don't know exactly how your relationships work, I am going to assume Head to Member is in 1:Many relationship. Purely for a more functional system. Also, because of new { target = "_blank"}, the Create view will start in new window.
Then we start on our [HttpGet] action:
public ActionResult Create(int id)
{
var temp = context.Heads.Find(id);
MembersViewModel tmp = new MembersViewModel
{
h_id = temp.h_id,
};
return View(tmp);
}
This will now return the a model to your 'Create' view with prepopulated h_id field. There shouldn't be much trouble from here regarding adding a new member with the prepopulated h_id that we worked through in your previous answer Saving ID from another table
This is more of a guideline than an exact copy paste answer, as I don't fully understand your system. Also, I see Title actually comes from another table, so the value isn't available directly from the 'Head' table, except an int value ID. This was my reason for not referencing the Title field.
Hope this helps you with your project

Categories

Resources