which situation use list<tablename> and tablename - c#

I am confused about which situation use public List<StudentViewModal> sm { get; set; } and public student stud { get; set; } ??
I create a table which name is student table and then create a ViewModel which name is StudentViewModal
student
public class student
{
public int id { get; set; }
public string name { get; set; }
public string address { get; set; }
public string city { get; set; }
public string country { get; set; }
}
StudentViewModal
public class StudentViewModal
{
public List<StudentViewModal> sm { get; set; }
public student stud { get; set; }
}
and then I create a home controller
HomeController.cs
public class HomeController : Controller
{
//here get the data from the database and display in the data table
public ActionResult Index()
{
return View();
}
//here I am performing insert update delete
public ActionResult Create()
{
return View();
}
and then after creating an IndexView
#model ListVsTable.Models.StudentViewModal //here I am performing sorting, searching in datatable? can I use here StudentViewModal for sorting, searching in the data table???
#{
ViewBag.Title = "Index";
}
<h2>Index</h2>
and then after creating a CreateView
#model ListVsTable.Models.student //here I am performing insert, update, delete operation? can I use here student table for insert update delete???
#{
ViewBag.Title = "Create";
}
<h2>Create</h2>
I am stuck on which situation use
ViewModel
public List<StudentViewModal> sm { get; set; }
and
table
public student stud { get; set; }
I am a student please help
which situation use student table only and StudentViewModal only
need help

Related

ASP.NET Core trouble in model binding

I'm new in ASp.NET Core. All data saved in database correctly, i tried show model data in View. Person model data gotten correctly, but second model Address didn't show in View. I suspect I made a mistake in the controller.
First model:
public class Person
{
public int PersonID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public Address HomeAddress { get; set; }
}
Second model:
public class Address
{
public int ID { get; set; }
public string Line { get; set; }
public string City { get; set; }
public string PostalCode { get; set; }
public string Country { get; set; }
public int PersonId { get; set; }
public Person Person { get; set; }
}
Controller code:
public IActionResult Index()
{
return View(_repository.Persons);
}
[HttpGet]
public ViewResult Create()
{
return View();
}
[HttpPost]
public IActionResult Create(PersonCreateViewModel p)
{
var obj = new Person
{
FirstName = p.FirstName,
LastName = p.LastName,
BirthDate = p.BirthDate,
HomeAddress = p.HomeAddress,
Role = p.Role,
IsApproved = p.IsApproved
};
_repository.Add(obj);
return View();
}
View:
#model IEnumerable<Person>
#{
ViewData["Title"] = "Home Page";
}
<div class="text-center">
#foreach(var p in Model)
{
<p>Name - #p.FirstName</p>
<p>Last Name - #p.LastName</p>
<p>Role - #p.Role</p>
<p>Line - #p.HomeAddress?.Line</p>
<p>City - #p.HomeAddress?.City</p>
}
<hr />
</div>
As the user Mustapha Larhrouch said in his comment, one way to fix this is to use the include method on your property to load related data, so _repository.Persons.Include(p => p.Adress)
There are several ways Entity Framework Core loads related data from Database like Eager loading, Explicit loading and Lazy loading, the method above is called Eager loading
I suggest you take a look at Loading Related Data from MS docs.
Or the lazy loading section in Querying in Entity Framework Core

MVC - Recordset Inside Foreach Loop

I am very new to .NET MVC and trying to learn MVC. I know that I am doing total wrong here, so I need your help. What I try to do is listing a set of 10 companies, then for each of those company listing the contacts based on the companyID. Please assume that the Entitites and DbContext are set properly, just the problem is between Controller and View is where I couldn't figure out how to:
Here is my Model:
namespace ERP.Models
{
[Table("ERP_Company")]
public class ERP_Company
{
[Key]
public int CompanyID { get; set; }
public string Name { get; set; }
}
[Table("ERP_CompanyContact")]
public class ERP_Contact
{
[Key]
public int ContactID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public int CompanyID { get; set; }
}
}
The methods for getting Company and Contact list from the database:
namespace ERP.Models
{
public class Method1
{
private ERPEntities db = new ERPEntities();
public List<ERP_Company> getCompanyList()
{
List<ERP_Company> companyList = (
from c in db.ERP_Company
where c.Name.Contains("Network")
select c).Take(10).ToList();
return companyList;
}
public List<ERP_Contact> getContactList(int CompanyID)
{
List<ERP_Contact> contactList = (
from cc in db.ERP_CompanyContact
where cc.CompanyID == CompanyID
select cc).Take(50).ToList();
return contactList;
}
}
}
Here is my controller where I am doing wrong:
namespace ERP.Controllers
{
public class Test1Controller : Controller
{
//private ERPEntities db = new ERPEntities();
Method1 _repository = new Method1();
public ActionResult Index()
{
ViewData["Company"] = _repository.getCompanyList();
ViewData["Contact"] = _repository.getContactList(CompanyID); // <-- Incorrect Here, but just to show that I want to pass the CompanyID
return View();
}
}
}
Lastly, the View which I want to list the Company, then query all contacts based on CompanyID and list them.
<ul>
#foreach (var item in ViewData["Company"] as List <ERP.Models.ERP_Company>
)
{
<li>#item.CompanyID | #item.Name</li>
<!-- Here is an EXAMPLE that I want to QUERY the Contact recordset and list all the contacts based on the CompanyID -->
<ul>
#for (var i = 0; i < 5; i++)
{<li>Contact #i</li>}
</ul>
}
</ul>
Is it possible to loop through the Contact model (or recordset) within a loop? How can I accomplish this?
Thanks in advance,
Here is how I would implement your case, not in a best way but in a simple way.
Entities:
public class Company
{
public int Id { get; set; }
public string Name { get; set; }
public ICollection<Contact> Contacts { get; set; }
}
public class Contact
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public int CompanyId { get; set; }
}
Service:
public class CompanyService
{
public List<Company> getCompanyList()
{
using (ERPEntities db = new ERPEntities())
{
return db.Companies
.Include("Contacts")
.Where(e => e.Name.Contains("Network"))
.Take(10)
.ToList();
}
}
}
Controller:
public HomeController(CompanyService companyService)
{
this.companyService = companyService;
}
public ActionResult Index()
{
List<Company> companies = this.companyService.getCompanyList();
return View(companies);
}
View:
<ul>
#foreach (var company in Model)
{
<li>#company.Id | #company.Name</li>
if (company.Contacts.Count > 0)
{
<ul>
#foreach (var contact in company.Contacts)
{
<li>#contact.FirstName</li>
}
</ul>
}
}
</ul>
In other hand, judging from your implementation, I feel like you may need to work more on fundamental skills like data structure, C#/OOP fundamental then ASP.NET MVC in respective order.

ASP.NET MVC Viewmodel returns nothing

Trying to make a simple application but my view returns nothing when trying to use a viewmodel. I assume the "db.[TableName].ToList();", which works when applied on a domain model, is not enough and the selection should happen in a different way when using a viewmodel, but I have no idea how to do it. Please help. Thank you.
Town.cs
using System.Collections.Generic;
namespace City.Models
{
public class Town
{
public Town()
{
Streets = new List<Street>();
}
public int TownId { get; set; }
public string TownName { get; set; }
public virtual ICollection<Street> Streets { get; set; }
}
}
Street.cs
using System.Collections.Generic;
namespace City.Models
{
public class Street
{
public Street()
{
Houses = new List<House>();
}
public int StreetId { get; set; }
public string StreetName { get; set; }
public virtual ICollection<House> Houses { get; set; }
}
}
House.cs
namespace City.Models
{
public class House
{
public int HouseId { get; set; }
public string HoueseName { get; set; }
public int StreetId { get; set; }
public virtual Street Street { get; set; }
}
}
Floor.cs
namespace City.Models
{
public class Floor
{
public int FloorId { get; set; }
public int FloorNumber { get; set; }
public int FireExtinguisherId { get; set; }
}
}
FireExtinguisher.cs
namespace City.Models
{
public class FireExtinguisher
{
public int FireExtinguisherId { get; set; }
public string FireExtinguisherName { get; set; }
public int FloorId { get; set; }
}
}
MyViewModel.cs
namespace City.Models
{
public class MyViewModel
{
public MyViewModel()
{
Town = new Town();
Street = new Street();
House = new House();
Floor = new Floor();
FireExtinguisher = new FireExtinguisher();
}
public int MyViewModelId { get; set; }
public Town Town { get; set; }
public Street Street { get; set; }
public House House { get; set; }
public Floor Floor { get; set; }
public FireExtinguisher FireExtinguisher { get; set; }
}
}
ApplicationDbContext.cs
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public DbSet<Town> Towns { get; set; }
public DbSet<Street> Streets { get; set; }
public DbSet<House> Houses { get; set; }
public DbSet<Floor> Floors { get; set; }
public DbSet<FireExtinguisher> FireExtinguishers { get; set; }
public DbSet<MyViewModel> MyViewModels { get; set; }
public ApplicationDbContext()
: base("DefaultConnection", throwIfV1Schema: false)
{
}
public static ApplicationDbContext Create()
{
return new ApplicationDbContext();
}
}
HomeController.cs (I think the problem lies here)
using System.Linq;
using System.Web.Mvc;
using City.Models;
namespace City.Controllers
{
public class HomeController : Controller
{
private ApplicationDbContext db;
public HomeController()
{
db = new ApplicationDbContext();
}
public ActionResult Index()
{
return View(db.MyViewModels.ToList());
}
public ActionResult About()
{
ViewBag.Message = "Your application description page.";
return View();
}
public ActionResult Contact()
{
ViewBag.Message = "Your contact page.";
return View();
}
}
}
Index.cshtml
#model IEnumerable<City.Models.MyViewModel>
<h2>Map information</h2>
<div class="container">
<table class="table">
<thead>
<tr>
<th>Town</th>
<th>Street</th>
<th>House</th>
<th>Floor</th>
<th>FireExtinguisher</th>
</tr>
</thead>
#foreach (var item in Model)
{
<tbody>
<tr>
<td>#(item.Town.TownName)</td>
<td>#(item.Street.StreetName)</td>
<td>#(item.House.HoueseName)</td>
<td>#(item.Floor.FloorNumber)</td>
<td>#(item.FireExtinguisher.FireExtinguisherName)</td>
</tr>
</tbody>
}
</table>
</div>
Even though I have test data in the db, this is all what I see when I run it:
Image is here
Please tell me what should I fix, how to get data retrieved. Thanks
EDIT #CrowdCoder
new picture here
I think your understanding about view model is incorrect.
View model is a class to transfer data between your view and your action method. View model is specific to the view. So if your view needs to display only 2 properties (Name and Age), your view model will have only those 2 properties. No need to bring all the properties from your entity model to the view model class.
I see that you added a new collection to the your db context,
public DbSet<MyViewModel> MyViewModels { get; set; }
This does not makes any sense. As i mentioned earlier, view models are UI concerns. It should not be in your data access code. Also do not mix the entities created by your ORM layer in your view model.
Also view models are simple POCOs. It should be lean-flat classes with properties. It is your responsibility to load the property values. You can do that in your action method or another method called from your action method.
Let's say you want to display a list of houses with it's street name, you will create a view model like this
public class HouseViewModel
{
public int HouseId { set; get;}
public string HoueseName { set;get;}
public string StreetName { set;get; }
}
Now in your view, you simply access these properties
#model IEnumerable<HouseViewModel>
<table>
#foreach(var item in Model)
{
<tr>
<td>#item.HouseId </td>
<td>#item.HoueseName </td>
<td>#item.StreetName </td>
</tr>
}
</table>
Ofcourse, for this code to work, you need to make sure you will be creating a list of HouseViewModel and send it to the view from your action method.
public ActionResult Index()
{
var list= new List<HouseViewModel>{
new HouseViewModel { HouseId =1,HoueseName ="Abc", StreetName ="Detroit"},
new HouseViewModel { HouseId =2,HoueseName ="Xyz", StreetName ="Novi"}
};
return View(list);
}
Now you can see that how we are using view model to transfer data from the action method to the view. Here we just hard coded the property values for the items in the list we are sending. We can update that to read from your EF db context as needed.
Let's read all the Houses, use LINQ projection to create a HouseViewModel object for each item in that collection and assign the property values.
public ActionResult Index()
{
var houses = db.Houses
.Select(a=>new HouseViewModel
{ HouseId =a.HouseId,
HoueseName =a.HouseName,
StreetName = a.Street.StreetName
})
.ToList();
return View(houses);
}

Which it is the best way to fill a dropdowlist in ASP.NET MVC

Which it is the best way in which you do not have to repeat the code in the Get and Post method to populate a DropDownList
That in view of creating and editing , I need to deploy some dropdowlist of related tables and do not want to be repeating viewbag in the GET and POST methods
Example :
A view where employees are recognized at an apartment, there is a Department employee relationship with.
public class Employee
{
public int EmployeeId { get; set; }
[DisplayName("Employee Name")]
[Required]
public string EmployeeName { get; set; }
[DisplayName("Department Id")]
public int DepartmentId { get; set; }
public virtual Department Department { get; set; }
}
public class Department
{
public int DepartmentId { get; set; }
[DisplayName("Department Name")]
[Required]
public string DepartmentName { get; set; }
public virtual ICollection<Employee> Employees { get; set; }
}
public class CompanyContext : DbContext
{
public DbSet<Employee> Employees { get; set; }
public DbSet<Department> Departments { get; set; }
}
And the controller method
public ActionResult Create()
{
ViewBag.DepartmentId = new SelectList(db.Departments, "DepartmentId", "DepartmentName");
return View();
}
[HttpPost]
public ActionResult Create(Employee employee)
{
if (ModelState.IsValid)
{
db.Employees.Add(employee);
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.DepartmentId = new SelectList(db.Departments, "DepartmentId", "DepartmentName", employee.DepartmentId);
return View(employee);
}
Move it to a method and call it in both the places. I recommend using a strongly typed view model for transferring data between your action method and view ,instead of using dynamic stuff like ViewBag and ViewData.
public class CreateUserVM
{
public int UserId {set;get;}
public string Name {set;get;}
public List<SelectListItem> Departments {set;get;}
public int SelectedDept {set;get;}
public CreateUserVM()
{
this.Departments = new List<SelectListItem>();
}
}
And in the GET action,
public ActionResult Create()
{
var vm = new CreateUserVM();
vm.Departments = GetDeperatements();
return View(vm);
}
private List<SelectListItem> GetDeperatements()
{
return db.Departments.Select(s=> new SelectListItem {
Value=DepartmentId.ToString(),
Text = "DepartmentName"
}).ToList();
}
Your view is bound to the CreateUserVM view model
#model YourNamespaceHere.CreateUserVM
#using(Html.BeginForm())
{
#Html.DropdownListFor(s=>s.SelectedDept,Model.Departments,"Select on")
#Html.TextBoxFor(s=>s.Name)
#Html.HiddenFor(s=>s.UserId)
<input type="submit" />
}
[HttpPost]
public ActionResult Create(CreateUserVM model)
{
if (ModelState.IsValid)
{
//Map the view model to entity
var emp = new Employee();
emp.Name = model.Name;
emp.DepartmentId = model.SelectedDept;
db.Employees.Add(emp);
db.SaveChanges();
return RedirectToAction("Index");
}
employee.Departments = GetDeperatements();
return View(employee);
}
For Your edit screen, You can use the same code as create action except you need to accept and id, Read the entity from db, map it to the viewmodel. (Set the SelectedDept id property value as well) and send it to the view.

MVC : Creating Database using Model class

I am following this MVC tutorial and trying to create a database using DbContext and related model classes. The project name is "odeToFood".
Model classes:
namespace odeToFood.Models
{
public class Restaurant
{
public int Id { get; set; }
public string Name { get; set; }
public string City { get; set; }
public string Country { get; set; }
public ICollection<RestaurantReview> Reviews { get; set; }
}
public class RestaurantReview
{
public int Id { get; set; }
public string Body { get; set; }
public int Rating { get; set; }
public int RestaurantId { get; set; }
}
public class odeToFoodDb :DbContext
{
public DbSet<Restaurant> Restaurants { get; set; }
public DbSet<RestaurantReview> Reviews { get; set; }
}
}
HomeController:
public class HomeController : Controller
{
odeToFoodDb _db = new odeToFoodDb();
public ActionResult Index()
{
var model= _db.Restaurants.ToList();
return View(model);
}
}
Index View
#model IEnumerable<odeToFood.Models.Restaurant>
#{
ViewBag.Title = "Home Page";
}
#foreach (var item in Model)
{
<div>
<h4>#item.Name;</h4>
Restaurant is in : #item.City #item.Country
<hr />
</div>
}
When I run this code, according to this tutorial it should create a database and the values should be fetched (when I enter in table) but in server explorer I cannot find a database.
Neither the Index View gives an error nor can I find a database in server explorer. I tried (Localdb)\v11.0 by going to "add connection" but still it does not show any database.
I would be grateful to know what's wrong.

Categories

Resources