我是.NET MVC的新手,正在尝试学习MVC。我知道我做的完全错了,所以我需要你的帮助。我尝试做的是列出一组10家公司,然后根据companyID列出每一家公司的联系人。请假设实体和DbContext设置正确,只是控制器和视图之间的问题是我不知道如何:
这是我的模型:
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; }
}
}从数据库中获取公司和联系人列表的方法:
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;
}
}
}下面是我的控制器的错误之处:
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();
}
}
}最后,我要列出公司的视图,然后根据CompanyID查询所有联系人并列出他们。
<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>是否可以在循环中遍历联系人模型(或记录集)?我如何才能做到这一点呢?
提前谢谢你,
发布于 2018-04-11 23:56:15
以下是我将如何实现您的案例,不是以最好的方式,而是以一种简单的方式。
实体:
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; }
}服务:
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();
}
}
}控制器
public HomeController(CompanyService companyService)
{
this.companyService = companyService;
}
public ActionResult Index()
{
List<Company> companies = this.companyService.getCompanyList();
return View(companies);
}视图:
<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>另一方面,从你的实现来看,我觉得你可能需要在基本技能上多下功夫,比如数据结构,C#/OOP基础,然后按各自的顺序学习ASP.NET MVC。
https://stackoverflow.com/questions/49758349
复制相似问题