我是.NET MVC的新手并且正在尝试学习MVC。我知道我在这里做错了,所以我需要你的帮助。我尝试做的是列出一组10家公司,然后为每家公司列出基于companyID的联系人。请假设Entitites和DbContext设置正确,只是控制器和View之间的问题是我无法弄清楚如何:
这是我的模特:
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>
是否可以在循环中循环接触模型(或记录集)?我怎么能做到这一点?
提前致谢,
答案 0 :(得分:0)
以下是我如何实施您的案例,而不是以最好的方式,而是以简单的方式。
<强>实体:强>
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。