I'm new in ASP.NET Core 3.1 and I'm trying to pass query data (entity framework) to view.
This is my query
public void OnGet()
{
var query = (from panier in _context.panier
join product in _context.product on panier.id_product equals product.Id_Product
where panier.username == HttpContext.Session.GetString("username")
select new
{
product.nom_product,
product.Image,
panier.Qte,
panier.prix,
panier.Prix_total
});
query.ToList();
}
But I don't know how to call the result in VIEW
You should define a list in your PageModel. Below is a simple example:
IndexModel:
public List<User> Users { get; set; }
public void OnGet()
{
Users = new List<User>
{
new User{ Id = 1, Name = "A"},
new User{ Id = 2, Name = "B"},
new User{ Id = 3, Name = "C"},
};
}
And in the view:
#page
#model IndexModel
#{
ViewData["Title"] = "Home page";
}
#foreach (var u in Model.Users)
{
<label>#u.Name</label><br />
}
Related
I've got two classes
public class Category
{
public int Id { get; set; }
public string Name { get; set; }
}
public class Item
{
public int Id { get; set; }
public sting Name { get; set; }
public Category Category { get; set; }
}
I have EF Migrations and the following seed:
var instockCategory = new Category() { Name = "InStock" };
var outofStockCategory = new Category() { Name = "OutOfStock" };
context.Items.AddOrUpdate(
d => d.Name,
new Item() { Name = "Item1", Category = instockCategory },
new Item() { Name = "Item2", Category = outofStockCategory },
new Item() { Name = "Item3", Category = outofStockCategory }
);
The line "d => d.Name" makes sure that based on the name of the item, there won't be duplicate records when I reseed the database.
However, the first time I execute this, two categories are created with id 1 and 2. But the second time I run this, 3 new categories are created!
Can I fix this without manually adding every single category first?
You have to use AddOrUpdate for your categories too.
var instockCategory = default(Category);
var outofStockCategory = default(Category);
context.Set<Category>().AddOrUpdate(
c => c.Name,
instockCategory = new Category() { Name = "InStock" },
outofStockCategory = new Category() { Name = "OutOfStock" }
);
context.Items.AddOrUpdate(
d => d.Name,
new Item() { Name = "Item1", Category = instockCategory },
new Item() { Name = "Item2", Category = outofStockCategory },
new Item() { Name = "Item3", Category = outofStockCategory }
);
An explicit DbSet on your Context class is not necessary.
public class Context : DbContext
{
public DbSet<Item> Items { get; set; }
}
1. Q #1
I have POCO
public class Product
{
public string Id { get; set; }
public string Name { get; set; }
public ICollection<Version> Versions { get; set; }
}
In my DbContext I have func
public void AttachUpdated<T>( T objectDetached) where T : class
{
var objContext = ((IObjectContextAdapter)this).ObjectContext;
var objSet = objContext.CreateObjectSet<T>();
var entityKey = objContext.CreateEntityKey(objSet.EntitySet.Name, objectDetached);
object original;
if (objContext.TryGetObjectByKey(entityKey, out original))
objContext.ApplyCurrentValues(entityKey.EntitySetName, objectDetached);
else
objContext.AddObject(entityKey.EntitySetName, objectDetached);}
So i want to add some Products to context
var p1 = new Product(){Id = "1", Name = "Product 1";}
var p2 = new Product(){Id = "1", Name = "Product 1";}
ctx.AttachUpdated(p1);
And when i try to add identical Product (with same Id as first product) TryGetObjectByKey() doesn't find already added product.
ctx.AttachUpdated(p2);
Therefore I need to use ctx.SaveChanges() or AccseptAllChanges() and then
ctx.AttachUpdated(p2) work as expected.
I can't understand where i have problem in my code.
Q #2
var p1 = new Product() { Id = "1", Name = "Product 1" };
var v1 = new Version() { Number = "1.0", Type = "Release", ReleaseDate = "01/01/13" };
p1.Versions = new List<Version>();
p1.Versions.Add(v1);
ctx.AttachUpdated(p1);
And then i see that v1 was addet to DbSet(). But why? And how i could prevent such bihavior. I need to add only Product and not related Versions.
public void AttachOrUpdate<T>(T entity) where T : class
{
var objContext = ((IObjectContextAdapter)context).ObjectContext;
var objSet = objContext.CreateObjectSet<T>();
var entityKey = objContext.CreateEntityKey(objSet.EntitySet.Name, entity);
var original = this.context.Set<T>().Find(entityKey.EntityKeyValues[0].Value);
if (original != null)
{
this.context.Entry<T>(original).CurrentValues.SetValues(entity);
}
else
objContext.AddObject(entityKey.EntitySetName, entity);
}
Basically what I want to do is return a read only string (user name) which is dependent on the navigation property User and just concatenates the first and last name together.
Ideally I'd just assign a value to OwnerUserId and then use the navigation property to retrieve the data if this is possible? I want to keep the model class as clean as possible.
Any ideas?
POCO Model
namespace Model
{
public class TicketReply
{
public int TicketReplyId { get; set; }
public string Title { get; set; }
/* ....more.... */
/* User ID FK */
public int OwnerUserId { get; set; }
/* User Navigation property */
[ForeignKey("OwnerUserId")]
[IgnoreDataMember]
public User User { get; set; }
/* Here is where I am stuck.... */
public string UserName
{
get { return User.FirstName + " " + User.LastName; }
set { }
}
}
}
*DB initialiser* - just to give some context
private List<TicketReply> AddReplies(DbContext context)
{
var replies = new List<TicketReply>
{
new TicketReply { TicketReplyId = 1, TicketId = 1, CreatedAt = DateTime.Now, OwnerUserId = 1, Text = "My initial query"},
new TicketReply { TicketReplyId = 2, TicketId = 1, CreatedAt = DateTime.Now, OwnerUserId = 2, Text = "Test reply."},
new TicketReply { TicketReplyId = 3, TicketId = 2, CreatedAt = DateTime.Now, OwnerUserId = 1, Text = "Test query"}
};
replies.ForEach(status => context.TicketReplies.Add(status));
context.SaveChanges();
return replies;
}
Thanks
Arthur
Roughly (and typing from memory)
Make it part of the User, e.g...
public class User
{
[NotMapped] // or from code "modelBuilder.Entity<User>().Ignore(x => x.UserName);"
public string UserName
// your user name implementation
}
You cannot just assign OwnerUserId and expect it to work - User will
be loaded when you load Ticket. Also you don't use 'OwnerUserId' in
your fk-entity - to search for for User.
You can use that to 'set' the User 'it points to' - it's saved when you first do the 'SaveChanges'.
e.g...
var user = new User {First = ... Second=...};
db.Tickets.Add(new Ticket{ User = user, ...});
// or...
db.Tickets.Add(new Ticket{ OwnerUserId = ownerid, ...}); // to point to exisitng one you know exists
db.SaveChanges();
...sometime later on...
var ticket = new Ticket { OwnerUserId = ownerid };
// ticket.User is null - won't work
var ticket = // tickets query // db.Tickets.Where(x => x.TicketId == ticketid).FirstOrDefault();
var username = ticket.User.UserName; // now it works, you have your User loaded
Or explicitely...
var user = db.Users.Where(x => x.UserId == ownerid).FirstOrDefault();
var username = user.UserName;
I have problem with the data that I select from table tblemployee that I want to bind it to the dropdownlist.
model
public class UserModels
{
public string EmployeeName { get; set; }
public int EmployeeCode { get; set; }
public IEnumerable<SelectListItem> Employee { set; get; }
}
Controller
public ActionResult Education() {
var query = (from e in context.tblEmployee_Employee
select new
{
empID = e.Code,
EmpName = e.NameEng
}
).ToList();
var model = new UserModels();
var _Emp = query;
foreach (var item in _Emp)
{
model.EmployeeCode = item.empID;
model.EmployeeName = item.EmpName;
model.Employee = new SelectList(_Emp, "EmpName", "EmpName");
}
return View(model);
}
View
<%= Html.DropDownListFor(x => x.EmployeeName, Model.Employee, "select EmployeeName")%>
And I got the error message "Object reference not set an instance of an object".Anyone know please kindly tell me how to solve it.
Thanks,
Try like this:
public ActionResult Education()
{
var model = new UserModels();
model.Employee = context
.tblEmployee_Employee
.ToList()
.Select(e => new SelectListItem
{
Value = e.Code.ToString(),
Text = e.NameEng
});
return View(model);
}
And make sure that your view is strongly typed to the UserModels view model and then:
<%= Html.DropDownListFor(
x => x.EmployeeName,
Model.Employee,
"select EmployeeName"
) %>
I am a new in asp.net mvc 2.0, I tried to search about this article but still can not get the answer like what I want.
I have one form to assign the role to each employee. So I create one form that I can input the employee's name and select the role that they are in. The role are taking from table Role. I used linq to sql to query the RoleName and RoleID from table Role, and want to bind it to DropDownListFor in my view.
I have one model :
public class UserModels
{
public string name { get; set; }
public string role { get; set; }
}
This is what I did in my controller :
[HttpPost]
public ActionResult UserMaintenance(FormCollection frm)
{
if (ModelState.IsValid)
{
EMP_DBSEntities context = new EMP_DBSEntities();
tblUserLogin user = new tblUserLogin();
user.UserName = frm["userLogin"].ToString();
IEnumerable<SelectListItem> role_list = context.tblRoles.Select(d => new SelectListItem
{
Value = d.RoleID.ToString(),
Text = d.RoleName
});
context.AddTotblUserLogins(user);
context.SaveChanges();
return View();
}
else
{
return View();
}
}
Can anyone tell me how could I bind the role_list to my DropDownListFor<> in my view.
Thanks.
In order to create a drop down list you need a view model with 2 properties: a scalar property that will contain the selected value and a collection property that will contain the available options.
So as always in ASP.NET MVC start by writing a view model:
public class UserRoleViewModel
{
[DisplayName("name")]
public string EmployeeName { get; set; }
[DisplayName("role")]
public int? SelectedRoleId { get; set; }
public IEnumerable<SelectListItem> Roles { get; set; }
}
then a controller:
public class HomeController : Controller
{
public ActionResult Index()
{
// fetch the roles
// could come from a database or something
var roles = new[]
{
new { RoleID = 1, RoleName = "Admin" },
new { RoleID = 2, RoleName = "Foo" },
new { RoleID = 3, RoleName = "Bar" },
new { RoleID = 4, RoleName = "Baz" },
};
// Now we build the model
var model = new UserRoleViewModel
{
EmployeeName = "John", // could come from a database or something
SelectedRoleId = 1, // could come from a database or something
Roles = new SelectList(roles, "RoleID", "RoleName")
};
return View(model);
}
[HttpPost]
public ActionResult Index(UserRoleViewModel model)
{
return Content(
string.Format(
"Selected role for {0} is {1}", model.EmployeeName, model.SelectedRoleId
)
);
}
}
and finally a view:
<%# Page
Language="C#"
MasterPageFile="~/Views/Shared/Site.Master"
Inherits="System.Web.Mvc.ViewPage<UserRoleViewModel>"
%>
...
<% using (Html.BeginForm()) { %>
<%= Html.EditorFor(x => x.EmployeeName) %>
<%= Html.DropDownListFor(x => x.SelectedRoleId, Model.Roles, "-- Role --") %>
<button type="submit">OK</button>
<% } %>