ASP.NET MVC - ViewModel嵌套循环

时间:2018-04-10 22:43:50

标签: c# asp.net-mvc razor

我是ASP.NET MVC的新手并试图列出一些公司,然后列出每个公司下的所有联系人。我想我已经接近让它发挥作用,所以如果可以,请帮助。

表和字段名称的模型:

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
    {
        public 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;
        }

        // This below method needs to get the passing CompanyID from getCompanyList for filtering.
        public List<ERP_Contact> getContactList()
        {
            List<ERP_Contact> contactList = (
                from cc in db.ERP_CompanyContact
                select cc).Take(50).ToList();
            return contactList;
        }

        /*  Tried this below, but not work for the Controller, maybe I am doing wrong.
        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;
        }
         */

    }
}

使用ViewModel(从其他帖子建议),结合两个模型:

namespace ERP.Models
{
    public class ViewModelDemoVM
    {
        public List<ERP_Company> allCompanies { get; set; }
        public List<ERP_Contact> allContacts { get; set; }
    }
}

Controller中的这段代码:

Method1 _repository = new Method1();
public ActionResult ViewModelDemo()
        {
            ViewModelDemoVM vm = new ViewModelDemoVM();
            vm.allCompanies = _repository.getCompanyList();
            vm.allContacts = _repository.getContactList();
            return View(vm);
        }

最后,视图代码:

@model ERP.Models.ViewModelDemoVM 

@{
    ViewBag.Title = "ViewModelDemo";
}

<h2>ViewModelDemo</h2>

<ul>
    @foreach (var company in Model.allCompanies)
    {         
        <li>@company.CompanyID | @company.Name</li>
        <ul>       
        <!-- HERE is I want to put the filtering... foreach contact WHERE CompanyID =  Model.allCompanies.CompanyID-->
        @foreach (var contact in Model.allContacts)
        {        
            <li>@contact.ContactID | @contact.FirstName</li>                             
        }
        </ul>
    }
</ul>

如何基于@company.CompanyID?示例代码过滤联系人(第二循环)将不胜感激。

提前致谢。

2 个答案:

答案 0 :(得分:1)

你可以在第二个循环中应用where子句。尝试以下代码。我希望这有帮助

using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEngine;
using SocketIO;
using UnityEngine.UI;

public class NetworkManager : MonoBehaviour {

public SocketIOComponent socket;
public Text serverMessageDebug;

private string latitude;
private string longitude;
private string coordinatesJson;

void Start() {

    latitude = "5"; //GPS.Instance.latitude.ToString();
    longitude = "5"; //GPS.Instance.longitude.ToString();

    //coordinatesJson = "{ 'latitude': '"+latitude+"', 'longitude': '"+longitude+"' }";
    coordinatesJson = "{\"latitude\":\"" + latitude + "\",\"longitude\":\"" + longitude + "\"}";
    Debug.Log(coordinatesJson);


    EstablishConnection ();
    //Subscrible to node.js websocket events
    socket.On ("test", OnTest);

}

#region Server Connection

public void EstablishConnection(){      
    StartCoroutine (ConnectToServer ());
}

private IEnumerator ConnectToServer(){      
    yield return new WaitForSeconds (0.5f);
    socket.Emit("client connect");
    socket.Emit("send coordinates", JSONObject.CreateStringObject(coordinatesJson));
    yield return new WaitForSeconds (1f);
}

#endregion
#region Websocket Events
private void OnTest(SocketIOEvent socketIOEvent){
    Debug.Log ("This is a test from the server");
    serverMessageDebug.text = "This is a test from the server";
    }
#endregion
}

答案 1 :(得分:1)

您应该创建一个具有嵌套结构的视图模型并使用它。请记住,视图模型特定于视图。因此,根据您的观点需要构建它。

public class CompanyVm
{
    public string Name { set; get; }
    public IEnumerable<ContactVm> Contacts { set;get;}
}
public class ContactVm
{
    public string Name { set; get; }
}
public class ViewModelDemoVM 
{
    public List<CompanyVm> Companies { set; get; }
}

您的联系人表/实体已具有公司实体/表格的外围密钥/导航属性。所以你要做的就是,让公司及其相应的客户,将其映射到我们的视图模型并在视图中使用它。

将集合类型添加到Company实体类以访问其联系人。

public class ERP_Company
{
    [Key]
    public int CompanyID { get; set; }
    public string Name { get; set; }
    public ICollection<Contact> Contacts { set; get; }
}

现在,在您的操作方法中,您可以获取数据

public IActionResult ViewModelDemo()
{
    var vm = new ViewModelDemoVM();
    vm.Companies = db.Companies
                     .Select(a => new CompanyVm { Name = a.Name,
                                                  Contacts = a.Contacts
                                                              .Select(c => new ContactVm
                                                                     { Name = c.Name })}
                      ).ToList();
    return View(vm);
}

现在在您看来,只需遍历公司并为每家公司循环浏览其联系人

@model ViewModelDemoVM 
@foreach(var company in Model.Companies)
{
    <h3>@company.Name</h3>
    <h5>Contacts</h5>
    @foreach(var contact in company.Contacts)
    {
        <p>@contact.Name</p>    
    }
}

一些注释

  1. 根据需要创建视图模型
  2. 不要将实体类(由ORM使用)与视图模型混合
  3. 在视图中保留较少的逻辑/ C#代码
  4. 我使用了类通用类名(Contact而不是ERP_Contact)和属性名称。使用上述代码时,如果需要,请进行必要的更改以使用现有名称。