Allow user to edit list items in MVC? - asp.net

I'm using Entity Framework Core to build a simple web app. For this app, I've created a model called Company that includes basic business info + a list of contacts (sales reps).
Here's my model:
public class Company
{
[Key]
public int ID { get; set; }
public string Name { get; set; }
public string Promo { get; set; }
public virtual List<Contact> Contacts { get; set; }
}
public class Contact
{
[Key]
public int ContactID { get; set; }
[ForeignKey("Company")]
public int CompanyID { get; set; }
public virtual Company Company { get; set; }
public string ContactName { get; set; }
public string ContactNumber { get; set; }
}
Here's the controller's index() method:
// GET: Companies
public async Task<IActionResult> Index()
{
List<Company> viewModelData = await _context.Companies
.Include(c => c.Contacts)
.ToListAsync();
return View(viewModelData);
}
Edit method:
// GET: Companies/Edit/5
public async Task<IActionResult> Edit(int? id)
{
if (id == null)
{
return NotFound();
}
var company = await _context.Companies
.Include(v => v.Contacts)
.FirstOrDefaultAsync(m => m.ID == id);
if (company == null)
{
return NotFound();
}
return View(company);
}
// POST: Companies/Edit/5
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(int? id, [Bind("ID,Name,Promo,Contacts")] Company company)
{
if (id == null)
{
return NotFound();
}
var companyToUpdate = await _context.Companies
.Include(v => v.Contacts)
.FirstOrDefaultAsync(m => m.ID == id);
if (await TryUpdateModelAsync<Company>(
companyToUpdate,
"",
i => i.Name, i => i.Promo, i => i.Contacts
)) {
try
{
await _context.SaveChangesAsync();
}
catch (DbUpdateException /* ex */)
{
//Log the error (uncomment ex variable name and write a log.)
ModelState.AddModelError("", "Unable to save changes. " +
"Try again, and if the problem persists, " +
"see your system administrator.");
}
return RedirectToAction("Index");
}
return View(companyToUpdate);
}
This is not correct since the code only allows me to edit Company info. How do I modify the code so that I can edit both Company & its contacts on the same edit view?

If you're purely looking to update values, then you can explicitly update them like so. A View Model is also recommended but this comes down to good vs bad practice. This omits the exception handling and serves only as an example of how to map these values, you'll have to modify the remainder of your controller to work directly with the CompanyEditViewModel
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(int? id, [Bind("ID,Name,Promo,Contacts")] CompanyEditViewModel company)
{
if (!ModelState.IsValid)
return RedirectToAction("Index");
var companyToUpdate = await _context.Companies
.Include(v => v.Contacts)
.FirstOrDefaultAsync(m => m.ID == id);
// Assign the new values
companyToUpdate.Name = company.Name;
companyToUpdate.Promo = company.Promo;
companyToUpdate.Contacts = company.Contacts?.ToList();
// Update and save
_context.Companies.Update(companyToUpdate);
await _context.SaveChangesAsync();
return View(companyToUpdate);
}
public class Company
{
public int ID { get; set; }
public string Name { get; set; }
public string Promo { get; set; } // Yes or No field
public List<Contact> Contacts { get; set; }
public class Contact
{
[Key]
public int ContactID { get; set; }
public int CompanyID { get; set; }
public string ContactName { get; set; }
public string ContactNumber { get; set; }
}
}
// The View Model contains the Company details which were modified
// The first Edit method will have to be updated to bind this View Model to the view
public class CompanyEditViewModel
{
public int ID { get; set; }
public string Name { get; set; }
public string Promo { get; set; }
public IList<Company.Contact> Contacts { get; set; }
}

Related

Many to Many crud operations in asp.net core

I have two entities (Product and Supply) that have a many-to-many relationship. I also have an entity between then that holds the two ID's (SupplyProduct).
My entities:
public class Product
{
[Key]
public int ProductId { get; set; }
[Required]
public string? ProductName { get; set; }
[Required]
[Column(TypeName = "decimal(6,2)")]
public decimal UnitPrice { get; set; }
public int Quantity { get; set; }
public string? Brand { get; set; }
public DateTime CreatedDateTime { get; set; } = DateTime.Now;
//Many to many relationship between the products and the stocks
public virtual ICollection<SupplyProduct>? SupplyProducts { get; set; }
}
public class Supply
{
[Key]
[Required]
public int SupplyId { get; set; }
[Required]
[DisplayName("Supply's Label")]
public string? Label { get; set; }
//One to many relationship between the Stock and the Merchant
public Merchant? Merchant { get; set; }
//Many to many relationship between the stocks and the products
public virtual ICollection<SupplyProduct>? SupplyProducts { get; set; }
}
public class SupplyProduct
{
[Key]
public int SupplyId { get; set; }
public virtual Supply? Supply { get; set; }
[Key]
public int ProductId { get; set; }
public virtual Product? Product { get; set; }
}
I want to assign a supply to a product while creating it . and then show the supply with it's associated products
this is my products controller:
ProductsController.cs
public class ProductController : Controller
{
private readonly ApplicationDbContext _db;
public ProductController(ApplicationDbContext db)
{
_db = db;
}
// GET: ProductController
public ActionResult Index()
{
IEnumerable<Product> ProductsList = _db.Products;
return View(ProductsList);
}
// GET: ProductController/Create
public ActionResult Create()
{
IEnumerable<Supply> SuppliesList = _db.Supplies.Include(s => s.Merchant);
ViewBag.Supplies = SuppliesList;
return View();
}
// POST: ProductController/Create
[HttpPost]
public ActionResult Create(Product model, List<int> supplyIds)
{
_db.Products.Add(model);
_db.SaveChanges();
SupplyProduct SP = new();
foreach (var supplyId in supplyIds)
{
SP.SupplyId = supplyId;
SP.ProductId = model.ProductId;
SP.Product = model;
SP.Supply = _db.Supplies.Where(x => x.SupplyId == supplyId).FirstOrDefault();
}
_db.SupplyProducts.Add(SP);
_db.SaveChanges();
return RedirectToAction(nameof(Index));
}
}
Can you please check my post Create method if it is as it should be, and how can I get the Products data while returning the Supplies in the Index method into the index view?
Thank you so much for your help and happy coding :D
Can you please check my post Create method if it is as it should be
Modify your code like below, otherwise you will always store the second supply in supplyIds:
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create(Product model, List<int> supplyIds)
{
_context.Product.Add(model);
_context.SaveChanges();
SupplyProduct SP = new();
foreach (var supplyId in supplyIds)
{
SP.SupplyId = supplyId;
SP.ProductId = model.ProductId;
SP.Product = model;
SP.Supply = _context.Supply.Where(x => x.SupplyId == supplyId).FirstOrDefault();
_context.SupplyProducts.Add(SP); //move to here...
_context.SaveChanges();
}
// _context.SupplyProducts.Add(SP);
//_context.SaveChanges();
return RedirectToAction(nameof(Index));
}
how can I get the Products data while returning the Supplies in the Index method into the index view?
Change your Index method like below:
// GET: Products
public async Task<IActionResult> Index()
{
var data = await _context.Product.Include(p => p.SupplyProducts)
.ThenInclude(sp => sp.Supply).ToListAsync();
return View(data);
}
You can remove the SupplyProduct tabble if there are no additional properties in anything other than Supply Product you don't need it for many-to many.
Then initialize the collections in the Supply and Product
public class Product
{
public Product()
{
this.Supplys = new HashSet<Supply>();
}
//... your props
public virtual ICollection<Supply> Supplys { get; set; }
}
public class Supply
{
public Supply()
{
this.Products = new HashSet<Product>();
}
//... your props
public virtual ICollection<Product> Products { get; set; }
}
Add Product to Supplys with only one query (in your code you make query for everyone Id in supplyIds)
[HttpPost]
public ActionResult Create(Product model, List<int> supplyIds)
{
//Get all supplys you need by id
var supplys = _db.Supplys
.Where(x => supplyIds.Contains(x.SupplyId))
.ToList();
//Add product in each supply
foreach (var supply in supplys)
{
supply.Products.Add(model);
}
//Update db
_db.SaveChanges();
return RedirectToAction(nameof(Index));
}
Get from DB
public ActionResult GetSuplys(List<int> supplyIds)
{
//Here you get all Supplys with the Products in it
var supplys = _db.Supplys
.Include(x => x.Products)
.Where(x => supplyIds.Contains(x.SupplyId))
.ToList();
//...
}
Save new Supply of Product
public ActionResult NewSuply()
{
var supply = new Supply
{
ProductName = name,
//Add all props you need
//You can add Product here or add empty collection
Products.Add(product), or = new List<Product>();
}
//No need to save Product separate
_db.Add(supply);
_db.SaveChanges();
}

Do I need set primary key in join table? MVC many to many relationship

As in question: is primary key in join table needed?
I have job table:
public partial class Job
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public Job()
{
this.Room = new HashSet<Room>();
}
public int JobID { get; set; }
public string Title { get; set; }
public Nullable<int> DepartmentID { get; set; }
public virtual Department Department { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<Room> Room { get; set; }
}
And user table:
public partial class AspNetUsers
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public AspNetUsers()
{
this.Department = new HashSet<Department>();
}
public string Id { get; set; }
public string Email { get; set; }
public bool EmailConfirmed { get; set; }
public string PasswordHash { get; set; }
public string SecurityStamp { get; set; }
public string PhoneNumber { get; set; }
public bool PhoneNumberConfirmed { get; set; }
public bool TwoFactorEnabled { get; set; }
public Nullable<System.DateTime> LockoutEndDateUtc { get; set; }
public bool LockoutEnabled { get; set; }
public int AccessFailedCount { get; set; }
public string UserName { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public Nullable<int> PhoneNo { get; set; }
public Nullable<System.DateTime> HireDate { get; set; }
public Nullable<System.DateTime> BirthDate { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<Department> Department { get; set; }
}
Every user can be in few departments, and every deparment can have many users.
In my controller:
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using Praca.Models;
using Praca.ViewModels;
namespace Praca.Controllers
{
public class EmployeeController : Controller
{
private Entities1 db = new Entities1();
// GET: Employee
public ActionResult Index(string id)
{
var viewModel = new AspNetUserDepartmentVM();
viewModel.AspNetUsers = db.AspNetUsers
.Include(i => i.Department)
.OrderBy(i => i.LastName);
if (id != null)
{
ViewBag.EmployeeID = id;
viewModel.Departments = viewModel.AspNetUsers.Where(
i => i.Id == id).Single().Department;
}
return View(viewModel);
}
// GET: Employee/Details/5
public ActionResult Details(string id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
AspNetUsers aspNetUsers = db.AspNetUsers.Find(id);
if (aspNetUsers == null)
{
return HttpNotFound();
}
return View(aspNetUsers);
}
// GET: Employee/Create
public ActionResult Create()
{
return View();
}
// POST: Employee/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see https://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "Id,Email,EmailConfirmed,PasswordHash,SecurityStamp,PhoneNumber,PhoneNumberConfirmed,TwoFactorEnabled,LockoutEndDateUtc,LockoutEnabled,AccessFailedCount,UserName,FirstName,LastName,PhoneNo,HireDate,BirthDate")] AspNetUsers aspNetUsers)
{
if (ModelState.IsValid)
{
db.AspNetUsers.Add(aspNetUsers);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(aspNetUsers);
}
// GET: Employee/Edit/5
public ActionResult Edit(string id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
AspNetUsers aspNetUsers = db.AspNetUsers
.Include(i => i.Department)
.Where(i => i.Id == id)
.Single();
PopulateAssignedCourseData(aspNetUsers);
if (aspNetUsers == null)
{
return HttpNotFound();
}
return View(aspNetUsers);
}
private void PopulateAssignedCourseData(AspNetUsers aspNetUsers)
{
var allCourses = db.Department;
var instructorCourses = new HashSet<int>(aspNetUsers.Department.Select(c => c.DepartmentID));
var viewModel = new List<AssignedDepartment>();
foreach (var course in allCourses)
{
viewModel.Add(new AssignedDepartment
{
DepartmentID = course.DepartmentID,
DepartmentName = course.DepartmentName,
Assigned = instructorCourses.Contains(course.DepartmentID)
});
}
ViewBag.Courses = viewModel;
}
// POST: Employee/Edit/5
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see https://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(string id, string[] selectedCourses)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
var instructorToUpdate = db.AspNetUsers
.Include(i => i.Department)
.Where(i => i.Id == id)
.Single();
if (TryUpdateModel(instructorToUpdate, "",
new string[] { "LastName"}))
{
try
{
UpdateInstructorCourses(selectedCourses, instructorToUpdate);
db.SaveChanges();
return RedirectToAction("Index");
}
catch (RetryLimitExceededException /* dex */)
{
//Log the error (uncomment dex variable name and add a line here to write a log.
ModelState.AddModelError("", "Unable to save changes. Try again, and if the problem persists, see your system administrator.");
}
}
PopulateAssignedCourseData(instructorToUpdate);
return View(instructorToUpdate);
}
private void UpdateInstructorCourses(string[] selectedCourses, AspNetUsers instructorToUpdate)
{
if (selectedCourses == null)
{
instructorToUpdate.Department = new List<Department>();
return;
}
var selectedCoursesHS = new HashSet<string>(selectedCourses);
var instructorCourses = new HashSet<int>
(instructorToUpdate.Department.Select(c => c.DepartmentID));
foreach (var course in db.Department)
{
if (selectedCoursesHS.Contains(course.DepartmentID.ToString()))
{
if (!instructorCourses.Contains(course.DepartmentID))
{
instructorToUpdate.Department.Add(course);
}
}
else
{
if (instructorCourses.Contains(course.DepartmentID))
{
instructorToUpdate.Department.Remove(course);
}
}
}
}
// GET: Employee/Delete/5
public ActionResult Delete(string id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
AspNetUsers aspNetUsers = db.AspNetUsers.Find(id);
if (aspNetUsers == null)
{
return HttpNotFound();
}
return View(aspNetUsers);
}
// POST: Employee/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(string id)
{
AspNetUsers aspNetUsers = db.AspNetUsers.Find(id);
db.AspNetUsers.Remove(aspNetUsers);
db.SaveChanges();
return RedirectToAction("Index");
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
db.Dispose();
}
base.Dispose(disposing);
}
}
}`
Unfortunately I have error: Unable to update the EntitySet 'AspNetUsersDepartment' because it has a DefiningQuery and no element exists in the element to support the current operation.
How can I solve this problem?
When i set primary key on that table, there is no many to many relationship but two one to many's relations.
OK. I have figuerd it out for myself..
If anyone also have this kind of problem:
You have to set primary keys, but not as separate value in your table.
In my case
CONSTRAINT [PK_dbo.AspNetUserDepartment] PRIMARY KEY CLUSTERED ([EmployeeId] ASC, [DepartmentId] ASC),
works perfectly.

The INSERT statement conflicted with the FOREIGN KEY constraint "FK_dbo.ConsoleUserInfoes_dbo.ConsolesCheckBoxes_consoleId"

I'm getting this error:
The INSERT statement conflicted with the FOREIGN KEY constraint "FK_dbo.ConsoleUserInfoes_dbo.ConsolesCheckBoxes_consoleId". The conflict occurred in database "aspnet-ForePlay-20180525122039", table "dbo.ConsolesCheckBoxes", column 'ConsoleId'.
I'm using Entity Framework and ASP.NET MVC 5 and IdentityUser and try to insert data form checkListBox to table into my database.
This is happening on the register view, when user need to register and fill the form.
public class ConsoleUserInfo
{
[Key]
public int identity { get; set; }
[Required]
[StringLength(255)]
[ForeignKey("User")]
public string userid { get; set; }
[Required]
[ForeignKey("consolesCheckBox")]
public int consoleId { get; set; }
public virtual ApplicationUser User { get; set; }
public virtual ConsolesCheckBox consolesCheckBox { get; set; }
}
This is the table that need to get a user id (form applictionUser) and consoleId
(form ConsolesCheckBox )
This is the ApplicationUserUser model class:
public class ApplicationUser : IdentityUser
{
[Required]
[StringLength(255)]
override
public string UserName { get; set; }
[Required]
[StringLength(50)]
public string Phone { get; set; }
public byte[] UserPhoto { get; set; }
public virtual UserAddress Address { get; set; }
public virtual ICollection<ConsolesCheckBox> consoleCheckBox { get; set; }
}
and this is the checkBoxList table:
public class ConsolesCheckBox
{
[Key]
public int ConsoleId { get; set; }
public string ConsoleName { get; set; }
public bool IsChecked { get; set; }
public virtual ICollection<ApplicationUser> ApplicationUser { get; set; }
}
This is my account controller, all in the register get and post
// GET: /Account/Register
[AllowAnonymous]
public ActionResult Register()
{
//using database
using (ApplicationDbContext dbo = new ApplicationDbContext())
{
//data will save list of the consoleCheckBoxItem
var data = dbo.consolesCheckBox.ToList();
// because the view is request a common model, we will create new one
CommenModel a = new CommenModel();
a.ConsolesCheckBoxList = data;
// we will need to return common model, that way we will return a
return View(a);
}
}
//
// POST: /Account/Register
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Register([Bind(Exclude = "UserPhoto")]CommenModel model)
{
if (ModelState.IsValid)
{
// To convert the user uploaded Photo as Byte Array before save to DB
byte[] imageData = null;
if (Request.Files.Count > 0)
{
HttpPostedFileBase poImgFile = Request.Files["UserPhoto"];
using (var binary = new BinaryReader(poImgFile.InputStream))
{
imageData = binary.ReadBytes(poImgFile.ContentLength);
}
}
var user = new ApplicationUser
{
UserName = model.registerViewModel.Email,
Email = model.registerViewModel.Email,
Phone = model.registerViewModel.Phone
};
user.UserPhoto = imageData;
var result = await UserManager.CreateAsync(user, model.registerViewModel.Password);
//after the user create, we will use the id and add the id to the userAddress table include
// Address, longitude and latitude.
using (ApplicationDbContext dbo = new ApplicationDbContext())
{
var currentUserId = user.Id;
var pasinfo = dbo.userAddress.FirstOrDefault(d => d.Userid == currentUserId);
if (pasinfo == null)
{
pasinfo = dbo.userAddress.Create();
pasinfo.Userid = currentUserId;
dbo.userAddress.Add(pasinfo);
}
pasinfo.Address = model.useraddress.Address;
pasinfo.latitude = model.useraddress.latitude;
pasinfo.longitude = model.useraddress.longitude;
dbo.SaveChanges();
foreach (var item in model.ConsolesCheckBoxList.Where(x => x.IsChecked).Select(x => x.ConsoleId))
{
var consoleUserInfo = new ConsoleUserInfo
{
userid = currentUserId,
consoleId = item
};
dbo.consoleUserInfo.Add(consoleUserInfo);
}
dbo.SaveChanges();
}
}
}
In the register GET I have a common model, because I used 3 models in the view
this is the common model:
public class CommonModel
{
public UserAddress useraddress { get; set; }
public RegisterViewModel registerViewModel { get; set; }
public List<ConsolesCheckBox> ConsolesCheckBoxList { get; set; }
}
I need your help here, I've been trying to fix this all day.

Can't receive the value of selectec item from Radio Button

So, I'm trying to do a online pool but I cant receive the value of selected item...
If someone can help me here is my Controller:
public async Task<IActionResult> Vote(int id, string text)
{
using (var poolDbContext = new PoolContext())
{
var Voted = new Vote();
var queq = new Answer { Id = id, Text = text };
// var Question = await poolDbContext.Questions.Include(s => s.Answers).AsNoTracking().SingleOrDefaultAsync(m => m.Id == id);
var Question = await poolDbContext.Questions.Include(A => A.Answers).AsNoTracking().SingleOrDefaultAsync(r => r.Id == r.Id);
if (Question == null)
{
return NotFound();
}
return View(Question);
}
}
[HttpPost, ActionName("Vote")]
[ValidateAntiForgeryToken]
public ActionResult VotePost(Question question)
{
try
{
if (ModelState.IsValid)
{
using (var poolDbContext = new PoolContext())
{
var id = question.Id.ToString();
var qId = question.Id;
var selectedAnswer = question.SelectedAnswer;
poolDbContext.SaveChanges();
// Save the data
return RedirectToAction("Index");
}
}
return View(question);
}
catch (DbUpdateException /* ex */)
{
ModelState.AddModelError("", "Unable to save changes. " + "Try again, and if the problem persists " + "see your system administrator.");
}
return View();
}
And also here are my Question Model:
public class Question
{
public Question()
{
Answers = new List<Answer>();
}
public int Id { get; set; }
public string Text { get; set; }
public virtual List<Answer> Answers { get; set; }
public DateTime StartDate { get; set; }
public DateTime EndDate { get; set; }
public Boolean Active { get; set; }
public string SelectedAnswer { set; get; }
}
Here is my Answer Model:
public class Answer
{
public int Id { get; set; }
public string Text { get; set; }
public int QuestionId { get; set; }
public List<Vote> Votes { get; set; }
}
And here is my Vote Model
public int Id { get; set; }
public string IpAdress { get; set; }
public DateTime VoteDate { get; set; }
public List<Question> Questions { set; get; }
public Vote()
{
Questions = new List<Question>();
}
}
My objective right now is to receive the vote from the Vote.Cshtml by the way here it is :
#model PoolManager.Models.Question
<div>
#Html.HiddenFor(x => x.Id)
<h3> #Model.Text </h3>
#foreach (var a in Model.Answers)
{
<p>
#Html.RadioButtonFor(b => b.SelectedAnswer, a.Id) #a.Text
#Model.SelectedAnswer
</p>
<input type="submit" />
}
So my objective is to receive the vote for each question and add the vote to the db, I don't know what i'm doing wrong..

Add in one controller checking other controller (asp.net mvc)

I have two model in my project, SupplierRow.cs
using System;
namespace Argussite.SupplierServices.ViewModels
{
public class SupplierRow
{
public Guid Id { get; set; }
public string FullName { get; set; }
public bool Subscribed { get; set; }
public bool Active { get; set; }
public int Visits { get; set; }
}
}
and UserRow.cs
using System;
namespace Argussite.SupplierServices.ViewModels
{
public class UserRow
{
public Guid Id { get; set; }
public string FullName { get; set; }
public string Name { get; set; }
public string Email { get; set; }
public int Status { get; set; }
public int Role { get; set; }
}
}
then I use the first model in one controller
public ActionResult Grid(bool? active)
{
var page = Context.Suppliers.AsNoTracking()
.WhereIf(active != null, e => e.Active == active)
.Select(e => new SupplierRow
{
Id = e.Id,
FullName = e.FullName,
Active = e.Active,
Visits = e.Visits
})
.ToList();
return PartialView("_Grid", page);
}
and use the second model in other controller
public class AdminSuppliersAccountsController : BaseController
{
public ActionResult Index(Guid id)
{
var supplierOfUser = Context.Suppliers.AsNoTracking()
//.Include(e => e.Supplier)
.FirstOrDefault(e => e.Id == id);
ViewData.Add("id", id);
ViewData.Add("SupplierFullName", supplierOfUser.FullName);
return View();
}
public ActionResult Grid(int? status, Pager pager, Guid? supplierId)
{
var page = Context.Users.AsNoTracking()
.Where(e => e.SupplierId == supplierId)
.WhereIf(status != null, e => (e.Status == status))
.Select(e => new UserRow
{
Id = e.Id,
FullName = e.FullName,
Email = e.Email,
Name = e.Name,
Status = e.Status,
Role = e.Role
})
.GetPage(pager, Sorter.Asc<UserRow, string>(e => e.FullName));
return PartialView("_Grid", page);
}
but I need to add in the first controller checking if all users from second model have status Inactive and then use that in the view.
How can I do that?
I guess, I need to add a new property in the first model public bool AllUnactive { get; set; } but what should I do then?

Resources