How to select from two table by id in mvc5 - c#

I'm new to MVC5,I had troubles with the problem.
can anybody help me?
I have 2 table, DocMain(Doc_Id,Doc_Title) , DocProduct(Doc_Id,Doc_Content),
I want to select the 2 table content by the same Doc_Id.
And loop them.
Display like:
<ul>
<li>title1content1</li>
<li>title2content2</li>
<li>title3content3</li>
</ul>
....
And how to do it?
//Here is my viewmodel
public class MainProductViewModel
{
public IEnumerable<DocMainListView> DocMainListView { get; set; }
public IEnumerable<DocProductListView> DocProductListView { get; set; }
}
-------------------------------------------------
//Here is my controller
public class DocProductController : Controller
{
private IDocProductRepository repository;
private IDocMainRepository repositoryMain;
public DocProductController(IDocProductRepository docProductRepository, IDocMainRepository docMainRepository)
{
this.repository = docProductRepository;
this.repositoryMain = docMainRepository;
}
public ActionResult List()
{
var products = from docProduct in repository.DocProduct
join docMain in repositoryMain.DocMain
on docProduct.Doc_Id equals docMain.Doc_Id
select new { DocMainTitle = docMain.Doc_Title, DocProductContent = docProduct.DocProduct_Content };
//ViewBag.products = products;
//DocProductListView model = new DocProductListView
//{
// DocProduct = repository.DocProduct
// .Join(repositoryMain.DocMain,
// docProduct => docProduct.Doc_Id,
// docMain => docMain.Doc_Id,
// (docProduct, docMain) => new { a = docMain.Doc_Id, b = docProduct.Doc_Id })
// .OrderByDescending(n => n.)
//};
return View(products);
}
}
I don't know how to write the controller code and View code.

As you want to display the title and content only, so your view model would be
public class MainProductViewModel
{
public IEnumerable<ProductInfo> Products { get; set;}
}
public class ProductInfo
{
public string DocMainTitle { get; set;}
public string DocProductContent { get; set;}
}
And your query would be:
var products = from docProduct in repository.DocProduct
join docMain in repositoryMain.DocMain
on docProduct.Doc_Id equals docMain.Doc_Id
select new ProductInfo { DocMainTitle = docMain.Doc_Title, DocProductContent =
docProduct.DocProduct_Content };
And assign this products to the Products of MainProductViewModel and return to view, then config your view as
#model MainProductViewModel

Related

MVC5/C#: Pass LINQ inner Join query to view model

i'm trying to pass data(.tolist) in inner join query to viewmodel, to use these data in view that contain also a partial view that needs data from viewModel.
public ActionResult IndexAdmin()
{
int userId = (int)Session["UserID"];
userInfo = _context.UserInfo.Find(userId);
var AllTours= (from p in _context.PostsInfo //Why this doesn't return two records
join r in _context.Region
on p.RegionId equals r.Id
where r.CountryId == 1
select new
{
RegionName = r.CountryId,
ImageName = p.ImageName,
}).Distinct().ToList();
//Here i need to define IndexAdminViewModel to populate tours and userInfo.username
return View(AllTours);
}
This is the IndexAdminViewModel:
public class IndexAdminViewModel
{
public string UserName { get; set; }
public string RegionName{get;set;}
public string ImageName {get;set;}
}
The view(IndexAdmin.cshtml)
#Html.Partial("_BarPartialAdmin", Model)
foreach (var post in Model)
{
<img src="~/images/#post.ImageName" alt="QfirstImage">
<h2>post.RegionName</h2>
}
The partial view will only needs the username to display it for once so i used to pass the model to partial view in order to use the username property, the RegionName and ImageName is a collection so that i can iterate over them and get teh values some way like use them in a table.
My question is how to pass the inner join query results AND theuserinfo.username to viewModel to use them in the view???????
You need to create 2 view models
public class ToursViewModel
{
public string RegionName { get; set; }
public string ImageName {get; set; }
}
public class IndexAdminViewModel
{
public string UserName { get; set; }
public IEnumerable<ToursViewModel> Tours {get;set;}
}
Then in the controller
public ActionResult IndexAdmin()
{
int userId = (int)Session["UserID"];
userInfo = _context.UserInfo.Find(userId);
IEnumerable<ToursViewModel> tours = (
from p in _context.PostsInfo
join r in _context.Region
on p.RegionId equals r.Id
where r.CountryId == 1
select new ToursViewModel
{
RegionName = r.CountryId,
ImageName = p.ImageName
});
IndexAdminViewModel model = new IndexAdminViewModel
{
UserName = userInfo.username,
Tours = tours
};
return View(model);
and in the view
#model IndexAdminViewModel
....
<h1>#Model.UserName</h1>
#foreach (var tour in Model.Tours)
{
<img src="~/images/#tour.ImageName" alt="QfirstImage">
<h2>#tour.RegionName</h2>
}
I you need to pass different objects to the view you basically have two options:
Create a composite class and use that as model
var allTours=
from p in _context.PostsInfo //Why this doesn't return two records
join r in _context.Region
on p.RegionId equals r.Id
where r.CountryId == 1
select new PostAndRegion
{
Region = r.CountryId,
Post= p.ImageName,
};
var model = new MyCompositeModel
{
PostsAndRegions = allTours.ToArray(),
UserInfo = null // or get from where you want to
};
return View(model);
with
public class PostAndRegion
{
public Post Post{get;set;}
public Region Region {get;set;}
}
public class MyCompositeModel
{
public IList<PostAndRegion> PostsAndRegions{get;set;}
public UserInfo MyUserInfo{get;set;}
}
Put some of the data in the ViewBag. see http://www.tutorialsteacher.com/mvc/viewbag-in-asp.net-mvc

can't get values in foreach from Viewbag mvc

I'm trying to get values from userList viewbag.i can't figure out the solution. Error is:
An exception of type 'Microsoft.CSharp.RuntimeBinder.RuntimeBinderException' occurred in System.Core.dll but was not handled in user code
Additional information: 'object' does not contain a definition for 'name'
though in ViewBag.userList contains data (2 objects) which i can see while debugging
#foreach (var aUser in ViewBag.userList)
{
<tr>
<td>#aUser.name</td>
<td>#aUser.username</td>
.....
<td>#Html.ActionLink("Edit", "UserEdit","Users")</td>
<td>#Html.ActionLink("Delete", "UserDelete", "Users")</td>
</tr>
}
I have a superclass and a childclass
superclass
public partial class user
{
public int id { get; set; }
public string name { get; set; }
public string username { get; set; }
...
public string user_role { get; set; }
}
childclass
public class UserSub: user
{
public string CreatedUserName { get; set; }
public string ModifiedUserName { get; set; }
}
In my controller i used linq to get values from database and stored it to Viewbag.userList. My controller function is
public ActionResult UserList()
{
IEnumerable<user> users = null;
users = dbEntities.users.ToList();
if (users != null)
{
var userLists = (from a in users join b in users on a.created_user_id equals b.id select new { a.name, a.username, a.password, a.user_role, a.is_enable, a.is_approved, CreatedUserName = b.name, a.create_time, a.is_android, a.device_id }).ToList();
ViewBag.userList = userLists;
}
return View();
}
tried List<UserSub> users=ViewBag.userList....getting error too
Use a ViewModel to share data between view and controller.
For example, first create the ViewModel:
public class userViewModel{
public int id { get; set; }
public string name { get; set; }
public string username { get; set; }
public string user_role { get; set; }
public string CreatedUserName { get; set; }
public string ModifiedUserName { get; set; }
...
}
You can put all data that you need in your view model... Then, I'll recommend you create a class in your model with all the queries that you need (you have to investigate how to do), but you can get the queries from your controller (if you want).
Well, edit your controller function:
public ActionResult UserList()
{
List<userViewModel> userVM = new List<userViewModel>(); //Important! Don't return all the query, just the data that you need.
IEnumerable<user> users = null;
users = dbEntities.users.ToList();
if (users != null)
{
var userLists = (from a in users join b in users on a.created_user_id equals b.id select new { a.name, a.username, a.password, a.user_role, a.is_enable, a.is_approved, CreatedUserName = b.name, a.create_time, a.is_android, a.device_id }).ToList(); //I'm going to suppose that your query is ok and you get all the data that you need...
foreach (var item in userLists)
{
userVM.Add(new userVM(){
userVM.name = item.name;
userVM.username = item.username;
userVM.user_role = item.user_role;
.......
});
}
}
return View(userVM); //return your view model
}
Finally, modify your view and call the ViewModel userViewModel
#model Model.ViewModel.userViewModel //It depends on the namespace
//Then try something likes this...
#foreach (var aUser in Model)
{
<tr>
<td>#aUser.name</td>
<td>#aUser.username</td>
.....
<td>#Html.ActionLink("Edit", "UserEdit","Users")</td>
<td>#Html.ActionLink("Delete", "UserDelete", "Users")</td>
</tr>
}
That's the idea, improve my answer. ;)

How to MVC C# Viewmodel to join data from multiple tables

Can anyone please tell me, I need to MVC C# Viewmodel join data from multiple tables and use chtml page #model ViewModels.StoreBrowseViewModel. But my logic will retrieve only one table data.
This is my class diagram. red box primary key, blue box foreign key
This is my StoreBrowseViewModel class
public class StoreBrowseViewModel
{
public int Id { get; set; }
public string Shape { get; set; }
public string Name { get; set; }
public string Clarity { get; set; }
public int CategoryID { get; set; }
public Category Category { get; set; }
public Shape Shapes { get; set; }
public IEnumerable<Gemstone> Gemstones { get; set; }
public IEnumerable<Clarity> Clarites { get; set; }
}
This is my action method.
public ActionResult Browse(string gemCategory = "")
{
var gemstones = from g in db.Gemstones
select g;
var category = db.Categories.Where(p => p.Name == gemCategory).FirstOrDefault();
gemstones = (gemstones.Include(s => s.Shapes)
.Include(c => c.Clarities)
.Where(p => p.CategoryID == category.CategoryID));
var viewModel = new StoreBrowseViewModel()
{
Category = category,
Gemstones = gemstones,
};
return this.View(viewModel);
}
This is my view model chtml page
#model ViewModels.StoreBrowseViewModel
grid.Column("Carat", header: "Weight " + Html.SortDirection(ref grid, "Carat")#item.Carat),
grid.Column("ShapeId", header: "Shape " + Html.SortDirection(ref grid, "Shape")#item.Shape),
grid.Column("ClarityId", header: "Clarity " + Html.SortDirection(ref grid, "Clarity")#item.Clarity),
grid.Column("Price", header: "Price(USD) " + Html.SortDirection(ref grid, "Price")#item.Price),
This is my out put It should display shape name and clarity name
I would do it differently from what im gona show below but this should help...
public ActionResult Browse(string gemCategory = "")
{
var category = db.Categories.FirstOrDefault(p => p.Name == gemCategory);
var gemstones = db.Gemstones.Include(s => s.Shapes)
.Include(c => c.Clarities)
.Include(c => c.Categories)
.Include(c => c.Cuts)
.Include(c => c.Orgins)
.Where(p => p.CategoryID == category.CategoryID);
var viewModel = new StoreBrowseViewModel() {Gemstones = gemstones};
return View(viewModel);
}
view model
public class StoreBrowseViewModel
{
public IEnumerable<Gemstone> Gemstones { get; set; }
}
in the view
#foreach(var item in Model.Gemstones)
{
<span>#item.Name</span>
#foreach(var item2 in Model.Gemstones.Clarities)
{
<span>#item2.Name</span>
}
}

How can i fill a value from one my domain model to my edit model?

In my project i have : countries and CountryEditModel.
public class countries
{
public int id { get; set; }
public string Code { get; set; }
public string Name { get; set; }
}
public class CountryEditModel
{
public int id { get; set; }
public string Code { get; set; }
public string Name { get; set; }
public bool isvalid{ get;set; }
}
countries is my domain model which is binded with entity framework and countryEditModel is the model which i use in my views.
How can i fill values from countries to countryEditModel. I actually want to bind list of all countries to dropdownlist in my view and I don't want to use my countries domain model directly in my view.
To solve i have done this
var countryDomain = context.Country.Select(c => c).ToList();
var countrylist = new List<CountryEditModel>();
var countrymodel = new CountryEditModel();
foreach (var country in countryDomain)
countrymodel = new CountryEditModel()
{
Code = country.Code,
Name = country.Name,
id = country.id
};
countrylist.Add(countrymodel);
Is there any better way?
Answer:
Actually this is what i exactly wanted to do
var countryViewModel = context.Country.Select(c => new CountryEditModel
{
Code = c.Code,
Name = c.Name,
id = c.id
}).ToList();
As indicated by the #rohitsingh this is what he exactly wanted to do
var countryViewModel = context.Country.Select(c => new CountryEditModel
{
Code = c.Code,
Name = c.Name,
id = c.id
}).ToList();

Join table and show in view using linq

This is my code
public List<InvoiceJoin> ShowIvoiceList()
{
InvoiceJoin ij = new InvoiceJoin();
List<InvoiceJoin> list;
var data = (from t in _Entity.TblInvoices join t0 in _Entity.TblClients on new { ReceiverCode = t.ReceiverCode } equals new { ReceiverCode = t0.ClientCode }
select new
{
t.RakeNumber,
t.ReceiverCode,
t.ConsigneeCode,
t.InvoiceNumber,
t.InvoiceDate,
t.RecordStatus,
t0.ClientCode,
t0.ClientDescription,
t0.ClientAddress1,
t0.ClientAddress2,
t0.ClientAddress3,
t0.ClientCity,
t0.ClientState,
t0.ClientCountry,
t0.ClientZipCode,
}).ToList();
foreach (var item in data)
{
list.Add(item);
}
return list;
}
my invoicejoin class
public class InvoiceJoin
{
public TblInvoice invoice { get; set; }
public string Cdetails { get; set; }
public string Cname { get; set; }
public string Caddr { get; set; }
public string Pname { get; set; }
public string Paddr { get; set; }
}
Its not working
I need to show two sql table data list in single view how i can do this in linq pls some ne help friends i need to show in html table. . .
make sure that you have class InvoiceJoin with constructor which take 2 parameters: invoice and client
class InvoiceJoin
{
private TblInvoice invoice;
private TblClient client;
public InvoiceJoin(TblInvoice invoice,TblClient client)
{
this.invoice=invoice;
this.client=client;
//...
}
public string RakeNumber{ get{return invoice.RakeNumber} set{invoice.RakeNumber=value;}}
//... ather invoice properties you want to see in grid
public string ClientCode{ get{return client.ClientCode} set{client.ClientCode=value;}}
// ...ather clientproperties you want to see in grid
}
loading data:
List<InvoiceJoin> data = (from invoice in db.TblInvoices
join client in db.TblClients
on invoice.ReceiverCode equals client.client
select new{Invoice=invoice,Client=client}).ToList()
.Select(n=>new InvoiceJoin(n.Invoice,n.Client)).ToList()
Use the LINQ Union method like this:
var data = (from t in _Entity.TblInvoices
join t0 in _Entity.TblClients on new { ReceiverCode = t.ReceiverCode } equals new { ReceiverCode = t0.ClientCode }
select new
{
t.RakeNumber,
t.ReceiverCode,
t.ConsigneeCode,
t.InvoiceNumber,
t.InvoiceDate,
t.RecordStatus,
t0.ClientCode,
t0.ClientDescription,
t0.ClientAddress1,
t0.ClientAddress2,
t0.ClientAddress3,
t0.ClientCity,
t0.ClientState,
t0.ClientCountry,
t0.ClientZipCode,
}).Union( // 2nd linq query with same result set as first here);

Categories