asp.net mvc linq I want to fetch two columns from two join table - linq

I have two tables join with PrId column, I have a view which show two columns from both tables, first column from first table and second column from second table. my actionresult is :
public ActionResult extrapoints()
{
ViewBag.dList = (from m in _session.customer
join p in _session.Products on m.PrId equals p.PrId
where m.UserId== 'john'
select new { FName = m.FName, price=p.price});
return View();
}
and in view i want to show both FName and price, I have following view :
#foreach (var item in ViewBag.dList)
{
<tr>
<td>#item.FName </td>
<td> #item.price</td>
</tr>
}
but is show error object' does not contain a definition for FName but when i use without Fname,price like
#foreach (var item in ViewBag.dList)
{
<tr>
<td>#item</td>
<td> #item</td>
</tr>
}
is shows :
{ FName = Shailendra, price= 1000 }
how to solve, please help

You Can Convert the Anonymous class to typed class, first add this class
class Test
{
public string FName { get; set; }
public decimal price { get; set; }
}
and make you linq statment as
ViewBag.dList = (from m in _session.customer
join p in _session.Products on m.PrId equals p.PrId
where m.UserId== 'john'
select new Test{ FName = m.FName, price=p.price});
and finally Cast the viewpage to type "Test"
#foreach (var item in (List<Test>)ViewBag.dList)
{
<tr>
<td>#item.Fname</td>
<td> #item.price</td>
</tr>
}

Related

Getting Microsoft.EntityFrameworkCore.Query.Internal.EntityQueryable`1[ProjectName.DTOs.ProjectDTO] instead of actual Data

I am working on my .NET MVC Core project. I am trying to get the project name by joining two tables using LINQ in my Controller.
My Controller code:
public IActionResult Projects()
{
var projectName = from p in _context.Tbl_Projects
join d in _context.Tbl_MyOfficeDocumets on p.Id equals d.Project_ID
select new ProjectDTO { ProjectName = p.ProjectName };
ProjectDTO proj = new ProjectDTO { ProjectName = projectName; }
return View(proj);
}
And Razor view page:
<table>
<tr>
<td>Your Projects</td>
<td>Description</td>
<td>Created On</td>
</tr>
#foreach(var item in Model.listOfProjects)
<tr>
<td>#Model.ProjectName</td> <-- Here I am getting that unusual response
<td>#item.Description</td>
<td>#item.CreatedOn</td>
</tr>
</table>
The #Model.ProjectName shows:
Getting Microsoft.EntityFrameworkCore.Query.Internal.EntityQueryable`1[ProjectName.DTOs.ProjectDTO]
Am I missing something?
You have created query and assigned it to DTO, which is wrong.
public IActionResult Projects()
{
var query = from p in _context.Tbl_Projects
join d in _context.Tbl_MyOfficeDocumets on p.Id equals d.Project_ID
select new ProjectDTO { ProjectName = p.ProjectName };
return View(query);
}

How to pass a more dynamic structure to jsp Spring Forms?

I have a structure:
public class Tabl {
String tableName;
List<String> tableColumns;
public Tabl() {
}
public String getTableName() {
return tableName;
}
public void setTableName(String tableName) {
this.tableName = tableName;
}
public List<String> getTableColumns() {
return tableColumns;
}
public void setTableColumns(List<String> tableColumns) {
this.tableColumns = tableColumns;
}
}
This form is emulating a table dynamically so to say. I have lots of simple tables with 1-2 columns except the id. I don't have an explicit assignment of fields as I have only one dynamic entity to hold them. The point of my question here is that I want to pass this tabl object and prepare a Spring form in jsp like this (I pass tableName from another JSP and it's ok:
#RequestMapping(value = "/addnew/{tableName}")
public String insertForm(#PathVariable("tableName") String tableName, Model m) {
Tabl tabl = new Tabl();
tabl.setTableName(tableName);
List<String> cols = spravochnikService.selectCols(tableName); //prepares structure by getting column names of the needed table (except the id): for example tableName=Employee, cols are firstname and lastname
tabl.setTableColumns(cols);
m.addAttribute("command", tabl);
return "insert_form"
}
insert_form.jsp:
<f:form action="${url_csave}">
<table border="1">
<c:forEach var="col" items="${command.tableColumns}">
<tr>
<td>
<c:out value="col" />
<f:input path="col" />
</td>
</tr>
</c:forEach>
<tr>
<td colspan="2" align="right">
<button>Save</button>
</td>
</tr>
</table>
</f:form>
When I try to do it it says invalid property "firstname" and invalid getter method. I can't have an explicit getter for it of course as all my tables are all in one dynamic entity. How to make Spring Forms understand the structure?

Selecting a single value using linq if already duplicate values exist in mvc4

I have a table
public class Product
public int Id { get; set; }
public string Model_Name { get; set; }
public string Company_Name { get; set; }
public Nullable<int> Price { get; set; }
public string Photo { get; set; }
Now the table contains multipe items so I just want to retrive the name of the company and dispay it. However the column Company_Name contains duplicate values. How do I need to check if it contains duplicate names then also display the value only once.I want to check it within view. Here is the View.
#foreach (var item in Model)
{
<tr>
//Anything extra could be added here to check the duplicate values
<td>#Html.ActionLink(item.Company_Name, "Brand",
new { Company_Name = item.Company_Name })
</td>
</tr
}
Here is how the table looks like
Id Model_Name Company_Name price photo
1 S7862 Samsung 1500 something
2 Galaxy Samsung 1500 something
3 Apple Apple 2000 something
4 Desire HTC 1500 something
5 Desire X2 HTC 1500 something
6 Nokia Lumia Nokia 1500 something
Now in the above table a few records are missing and if I write
#foreach(var item in Model)
{
<tr>
<td>
#Html.ActionLink(item.Company_Name, "Brand", new {Company_Name=item.Company_Name})
</td>
</tr>
}
now here I get the result as
Brand
Samsung
Samsung
Apple
HTC
HTC
Nokia
I want it to be as
Brand
Samsung
Apple
HTC
Nokia
Any ideas will be appreciated. I want the Linq to come within the view.
Try using a Distinct() on that Property:
#foreach (var companyName in Model.Select(m => m.Company_Name).Distinct())
{
<tr>
//Anything extra could be added here to check the duplicate values
<td>#Html.ActionLink(companyName, "Brand",
new { Company_Name = companyName })
</td>
</tr
}
How about Grouping them on Company_Name:
#{
var grouped = Model.GroupBy(x=>x.Company_Name);
}
#foreach (var item in grouped)
{
<tr>
//Anything extra could be added here to check the duplicate values
<td>#Html.ActionLink(item.Key"Brand",
new { Company_Name = item.Key })
</td>
</tr
}

Incorporating custom view model data from multiple tables into a view

I can't understand why I can't find anything that clearly explains how to do this with MVC. Seems like a pretty routine issue:
I have three tables:
PackageName: PackageNameID,PackageName
Food: FoodID,Food
PackageContent: PackageContentID, PackageNameID, FoodID, Qty
The application is supposed to describe packages of food. For example, a package named "A" might contain 4 onions and 3 peppers. Another package, "B", might contain 2 rolls and 2 onions.
Currently I have a custom view model ("PackageNameModel") that collects the data:
public ViewResult Index() {
var viewModel =
from pn in db.PackageNames
from pc in db.PackageContents
.Where(p => p.PackageNameID == pn.PackageNameID).DefaultIfEmpty()
from f in db.Foods
.Where(f => f.FoodID == pc.FoodID).DefaultIfEmpty()
select new PackageFoodModel { PackageName = pn, PackageContent = pc, Food = f };
return View( viewModel );
}
This returns the data correctly, but what do I do with it so that the view is actually one that is useful for the application?
Using this in my view:
#foreach (var item in Model) {
<tr>
<td>
#Html.DisplayFor(modelItem => item.PackageName.PackageName1 ) ,
#Html.DisplayFor(modelItem => item.Food.Food1)=#Html.DisplayFor(modelItem => item.PackageContent.Qty)
</td>
<td>
#Html.ActionLink("Edit", "Edit", new { id=item.PackageName.PackageNameID }) |
#Html.ActionLink("Details", "Details", new { id = item.PackageName.PackageNameID }) |
#Html.ActionLink("Delete", "Delete", new { id = item.PackageName.PackageNameID })
</td>
</tr>
}
I am able to display the following:
- A , Onions=4 Edit | Details | Delete
- A , Peppers=3 Edit | Details | Delete
- B , Rolls=2 Edit | Details | Delete
- B , Onions=2 Edit | Details | Delete
This is not very useful. What I'm trying to do is display something like this:
- A (Onions=4,Peppers=3) Edit | Details | Delete
- B (Rolls=2,Onions=2) Edit | Details | Delete
Eventually, the next page down after navigating to the "Edit" action would provide an editable name for the package as well as a table of all available foods and an adjacent quantity box so that the foods/quantities within each package may be updated.
Can anyone explain how this is done within the MVC framework?
All the tutorials I have seen on the web/in books deal with data that is much simpler. Can anyone point me to some sample code / tutorials that deal with something like this?
Thanks in advance!
You need to aggregrate your results.
Create a view model like this
public class PackageViewModel
{
public int ID { set;get;}
public string Name { set;get;}
public List<FoodItem> FoodItems { set;get;}
public PackageViewModel()
{
FoodItems=new List<FoodItem>();
}
}
public class FoodItem
{
public string FoodName { set;get;}
public int Quantity { set;get;}
}
and in your Get action, You need to do the aggregate the data from your data which is ccoming from your data access layer and fill to the ViewModel List
public ActionResult IndeX()
{
List<PackageViewModel> listVM=new List<PackageViewModel>();
//Get your data and do aggregation and fill in listVM
return View(listVm)l
}
and in our view,
#model List<PackageViewModel>
#foreach(var item in Model)
{
<tr>
<td>#item.Name</td>
<td>
foreach(var food in item.FoodItems)
{
#food.FoodName - #food.Quantity
}
</td>
<td>
#Html.ActionLink("Edit","Edit",new {#id=item.ID})
</td>
</tr>
}

ASP.NET MVC How to pass a joined data into view?

I have the following code in my controller:
public ViewResult Index()
{
var q = from ci in db.City
join co in db.Country on ci.CityID equals co.CityID
select ci;
return View(q);
}
the database are as follow:
Table City: CityID, CityName
Table Country: CountryID, CountryName
in the index view how do I display both the CityName and CountryName:
#foreach (var item in Model) {
#Html.DisplayFor(modelItem => item.CityName)
and I can't get it to display CountryName :(
Thanks!
It doesn't work because you're only selecting the city in your query. You need to select both. Using an anonymous object is one way:
select new { City = ci, Country = co }
You should then be able to access item.City.Cityname, item.Country.CountryName etc.

Resources