This is my controller:
public ActionResult product_list()
{
using(myDatabaseEntities1 d=new myDatabaseEntities1())
{
var a = (from g in d.departments
from p in d.Tables
where p.userid == g.kod_achrai
select new { department_name = g.department_name, oved_achrai = p.fullname, teur = g.teur });
return View(a);
}
}
The select statement base on 2 tables,
I want to show this in view.
I create a view but i dont know what to put in title
exp: #model MvcApplication4.department
I attach picture of option:
Can someone help me :)
Thank in advance.
I think you want to do scaffolding , so You have to create a model class for it. like
public class deptModel
{
public string department_name { get; set; }
public string oved_achrai { get; set; }
public string teur { get; set; }
}
and in your code write this
public ActionResult product_list()
{
using(myDatabaseEntities1 d=new myDatabaseEntities1())
{
var a = (from g in d.departments
from p in d.Tables
where p.userid == g.kod_achrai
select new deptModel { department_name = g.department_name, oved_achrai = p.fullname, teur = g.teur });
return View(a);
}
}
And thin in this model class list you will find deptModel ,to use/select.
and for using two tables yo can use join if you want like this.
var a = (from g in d.departments
join p in d.Tables
on p.userid equals g.kod_achrai
select new deptModel{ department_name = g.department_name, oved_achrai = p.fullname, teur = g.teur });
and whatever you meant by title exp will be #model MvcApplication4.deptModel
you can use scaffolding template like this in your solution
hope it will help you
Related
I am developing an application in asp.net MVC, and for show multi-table in the same view, I have created one big ViewModel which contains the three models (employee, user, and request)
now my problem is my query that not work, and I can't locate the problem
Thank you for your help
Sorry for my english is not good
My bigviewmodel
namespace freegest.Models
{
public class ControleViewModel
{
public List<employe> employes { get; set; }
public List<demande > demandes { get; set; }
public List<utilisateur> utilisateurs { get; set; }
}
}
My query
public ActionResult listdemande()
{
int id = Convert.ToInt32(Session["id_utilisateur"]);
ControleViewModel CV = new ControleViewModel();
CV = (from a in CV.utilisateurs
join b in CV.demandes
on a.id_utilisateur equals b.idutilisateur_demande
join c in CV.employes
on a.idemploye_utilisateur equals c.id_employe
orderby c.nom_employe ascending
where a.id_utilisateur == id
select new ControleViewModel
{
c.nom_employe ,
});
return View(CV);
}
Try the following approach to join multiple tables using LINQ:
public ActionResult Index()
{
using (DBEntities db=new DBEntities())
{
List<Employee> employees = db.Employees.ToList();
List<Department> departments = db.Departments.ToList();
List<Incentive> incentives = db.Incentives.ToList();
var employeeRecord = from e in employees
join d in departments on e.Department_Id equals d.DepartmentId into table1
from d in table1.ToList()
join i in incentives on e.Incentive_Id equals i.IncentiveId into table2
from i in table2.ToList()
select new ViewModel
{
employee=e,
department=d,
incentive=i
};
return View(employeeRecord);
}
}
I'm trying to populate a Kendo dropdown using a Read function in a controller, but do so in a way that allows me to get items from one table or a view, based on a column in the view.
Ex.
public class AlternateCountry // <-- Table
{
public Guid CountryGUID { get; set; }
public string Name { get; set; }
}
public class Countries // <-- View
{
public bool hasAltName { get; set; }
public Guid GUID { get; set; }
public string Name { get; set; }
}
I want to show the "Countries" Name column value unless we have an alternate name for that country. Then it would show the Name column in the "AlternateCountry" table. Something like:
var getCountries = (from c in db.Countries
join alt in db.AlternateCountry on c.GUID equals alt.CountryGUID
where c.hasAltName == true
select new {
GUID = c.GUID,
Name = alt.Name
}).ToList();
return Json(getCountries, JsonRequestBehavior.AllowGet);
Problem is this doesn't account for when the alternate name is false, to grab "Name" from the Countries view. I can duplicate another of these blocks and change c.hasAltName == false, but how do I then combine both of these into one DataSourceResult set?
Actually, I was able to solve this with a union of two queries -- one for the ones without alternate names, one for those with alternate names:
var realCountries = (from c in db.Countries
where c.hasAltName == false
select new {
GUID = c.GUID,
Name = c.Name
}).ToList();
var fakeCountries = (from c in db.Countries
join alt in db.AlternateCountry on c.GUID equals alt.CountryGUID
where c.hasAltName == true
select new {
GUID = alt.GUID,
Name = alt.Name
}).ToList();
var allCountries = realCountries.Union(fakeCountries);
return Json(allCountries, JsonRequestBehavior.AllowGet);
I am working with MVC5 and I am trying to display 1 image per number in an int, for example:
If the rating is 5, show 5 stars.
I have found a way to do this but it's a real horrible work around, I would prefer to understand how to right the foreach loop on this.
CODE:
public class RestaurantReview
{
public int Id { get; set; }
public string Name { get; set; }
public string City { get; set; }
public string Country { get; set; }
public int Rating { get; set; }
}
=========================================================
public ActionResult Index()
{
var model =
from r in _reviews
orderby r.Name descending
select r;
return View(model);
}
=========================================================
Example of Data Source:
static List<OdeToFood.Models.RestaurantReview> _reviews = new List<RestaurantReview>
{
new RestaurantReview {
Id = 1,
Name = "Cinnamon Club",
City = "London",
Country = "UK",
Rating = 10,
},
you do this with CSS really, for example. you html may look like this:
foreach(var item in model.items){
<span id="star#(item.rating)"> </span>
<span>#mitem.name</span>
}
I dont agree with this hard coded solution, but you could do this:
var model =
from r in _reviews
orderby r.Name descending
select new { name = r.name, image = "star" + r.rating, field3 = r.blah, field4 = r.blahblah }
However as explained below, you change the image, you have to change the code, if you change the image location, you also have to change your code. If you want to change the ratings. You have to change our code.
another solution is client side: http://wbotelhos.com/raty
or something similar. https://www.google.co.uk/search?q=jquery+ratings&oq=jquery+ratings&aqs=chrome..69i57j0l5.3043j0j7&sourceid=chrome&espv=210&es_sm=122&ie=UTF-8
A simple for loop would do this:
for (i=0; i < item.Rating; i++) {
<img src="star">
}
Let's say I have two models:
public class User
{
[Key]
public int UserId { get; set; }
public string Name { get; set; }
}
and
public class Friend
{
[Key]
public int FriendId { get; set; }
public User A { get; set; }
public User B { get; set; }
}
Let's say I only have 2 users in my database (ids: 1 (Jon) and 2 (Sam)). Now I insert into table friend like this:
db.Friends.Add(new Friend()
{
A = db.Users.Find(1),
B = db.Users.Where(u => u.UserId == 2).First()
});
db.SaveChanges();
Suddenly, I find a user (3, Sam) in a table user. What is the reasoning behind this? Not completely sure if relevant or not, but note that even if I make A and B fields virtual, nothing changes.
UPDATE
Finally found how to reproduce my problem. Apparently the problem isn't exactly the same as I described.
User a, b;
using (var db = new DbConnection())
{
a = db.Users.First(u => u.UserId == 1);
b = db.Users.First(u => u.UserId == 2);
}
using (var db = new DbConnection())
{
db.Friends.Add(new Friend()
{
A = a,
B = b
});
db.SaveChanges();
}
Now users will have 4 users. Does it mean that if I step out of transaction, I can no longer access the entities as if they were exactly the same items in the current transaction? Or maybe there is a way to make the program know that I am referring to the same item (because the ID is the same)?
Honestly tried the same steps as you described and everything work well.. Anyway my steps
Created a db context class derived from `DbContext'
public class EFContext : DbContext
{
public DbSet<Friend> Friends { get; set; }
public DbSet<User> Users { get; set; }
public EFContext(string connectionString)
: base(connectionString)
{
}
}
I use MSQL2008 Express with win auth so I created the Users table
using (var db = new EFContext(#"Data Source=yourMachineName\SQLEXPRESS2008;Initial Catalog=DBName;Integrated Security=True;MultipleActiveResultSets=True"))
{
db.Users.Add(new User()
{
UserId = 1,
Name = "John"
});
db.Users.Add(new User()
{
UserId = 2,
Name = "Sam"
});
db.SaveChanges();
}
I checked my db and found 2 records
After I created the Friends table
using(var db = new EFContext(#"Data Source=yourMachineName\SQLEXPRESS2008;Initial Catalog=DBName;Integrated Security=True;MultipleActiveResultSets=True"))
{
db.Friends.Add(new Friend()
{
A = db.Users.Find(1),
B = db.Users.Where(u => u.UserId == 2).First()
});
db.SaveChanges();
}
Again I got 1 record in the Friends table with columns FriendId=1, A_UserId=1, B_UserId=2.
I checked the Users table and I still have 2 records.
If I were you I would try my code in a separate app. If it works then please post here all steps which led you to this problem.
I am new in mvc 4 but getting progress. I'm getting crazy with something which how i can select an item in select list in view model.
here is my controller code;
ViewBag.DepartmanListesi = new SelectList(VeriTabani.UnvanDepartmanlaris, "UDepId", "Departman");
and in my view model I am listing a diffirent database but in this list one field includes an id of the UnvanDepartmanlaris.instead of showing the id, I want to show name of the id. but what I have tried is not worked. can you please help me.
I searched many things but most of them was about how to set dropdownlist. I couldnt find any answer of my question.
Thank you in advance. I will be waiting for any response
Try this,
Controller
public List<CustomerModel> GetCustomerName()
{
// Customer DropDown
using (dataDataContext _context = new dataDataContext())
{
return (from c in _context.Customers
select new CustomerModel
{
CustomerId = c.CID,
customerName = c.CustomerName
}).ToList<CustomerModel>();
}
}
[HttpGet]
public ActionResult CustomerInfo()
{
var List = GetCustomerName();
ViewBag.CustomerNameID = new SelectList(List, "CustomerId", "customerName");
return View();
}
View
#Html.DropDownList("CustomerId", (SelectList)ViewBag.CustomerNameID, "--Select--")
Model
public class CustomerModel
{
public int CustomerId { get; set; }
public string customerName { get; set; }
public List<SelectListItem> customerNameList { get; set; }
}
I'm using following approach. Hope it helps:
Create helper class (I'm having here all my selectlists)
Public static class Helper
{
public static List<SelectListItem> GetList()
{
var result = new List<SelectListItem>();
var ctx = new YourContext();
var items = from n in ctx.Clients
select new SelectListItem
{
Text = n.Client.Name,
Value = n.ClientID.ToString()
};
foreach (var item in items)
result.Add(item);
return result;
}
}
Than in your View:
#Html.DropDownList("GetClients", Helper.GetList())
Works for me.