ASP.NET Core trouble in model binding - c#

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

Related

which situation use list<tablename> and tablename

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

Having trouble with Entity Framework and relationships

I'm having difficulty understanding how to create relationships with the entity framework. (I'm using the MVC architecture, and code first migrations )for example, if I have a class
public class Employee
{
public int Id { get; set; }
public string PIN { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
and I have another class, let's say for example I wish to track employees hours
public class EmployeeHours
{
public int Id { get; set; }
public DateTime? ClockIn { get; set; }
public DateTime? ClockOut { get; set; }
public Employee emplyee { get; set; }
}
I'm having a difficult time understanding how I can have these two classes to interact with each other. Like if John Smith's PIN is 1234, and he enters his PIN into a textbox, how do I successfully add his clock in time and date to the employee hours class?
and if I have a view that looks like this for the employee to enter their PIN
#using (Html.BeginForm("ClockIn", "Login"))
{
#Html.LabelFor(c => c.Employee.PIN)
#Html.TextBoxFor(c => c.Employee.PIN)<br />
<button type="submit">Save</button>
}
and the clockIn controller looks like this
[HttpPost]
public ActionResult ClockIn(string Pin)//employee clocking in
{
_context.EmployeeHours.Add();
_context.SaveChanges();
return View();
}
I'm trying to figure out how to store the time and date associated with this employee in the class, so I can go back and see when this employee clocked in. Thanks!
Add a Navigation Property to Employee, EG:
public class Employee
{
public int Id { get; set; }
public string PIN { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public virtual ICollection<EmployeeHours> Hours { get; } = new HashSet<EmployeeHours>();
}
Then use it something like this:
[HttpPost]
public ActionResult ClockIn(string pin)//employee clocking in
{
var emp = _context.Employees.Where(e => e.Pin == pin).First();
var hours = new EmployeeHours();
hours.StartTime = DateTime.Now;
//...
emp.Hours.Add(hours);
_context.SaveChanges();
return View();
}

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.

Cannot show products (courses) in my MVC project

i need help with my MVC Project.
My page will shown avaible Courses so i need to show Courses on page
my code looks like this but doesnt work
i try to show properties for Courses from CourseViewModel in
public ActionResult Index()
{
var viewModel = new List<CourseViewModel>();
CourseViewModel Courses = new CourseViewModel();
Courses = new CourseViewModel();
return View(viewModel);
}
would be so glad if someone could help me..
Assuming your class looks like this based on your comments
public class CourseViewModel {
public int CourseId { get; set; }
public string CourseName { get; set; }
public string CoursePlace { get; set; }
public string CourseLevel { get; set; }
public string CourseDate { get; set; }
public string CourseDescription { get; set; }
public string CourseBookUrl { get; set; }
}
You populate your list to pass as the viewmodel for your view
public ActionResult Index() {
var viewModel = new List<CourseViewModel>();
//Either get the viewmodels from a data source or add them yourself
var course = new CourseViewModel() {
CourseId = 1,
CourseName = "Maths 101",
CoursePlace = "Some class room",
CourseLevel = "1",
CourseDate = "",
//..populate other properties
};
viewModel.Add(course);
//repeat to add more courses
return View(viewModel);
}
In your view you specify what type the view model is
#model List<CourseViewModel>
and you can traverse the model and display the details.
#foreach (var course in Model) {
<div>#course.CourseName</div>
<!--other details you want to display-->
}

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