c# - 如何在 MVC ASP .net C# 的 .cshtml 文件中使用嵌套 foreach 循环

标签 c# asp.net-mvc razor foreach

我正在创建一个应用程序,在其中使用 Mysql 数据库从两个不同的表中检索数据。我正确地获取了该数据,但问题是,当我尝试使用 foreach 循环在 View 上显示它时,数据不会以正确的方式显示。

这是我的代码:

Controller

public ActionResult me()
{

      ViewAllData objviewalldata = new ViewAllData();
      // var emp1 = db.emps.FirstOrDefault(e => e.empid == 1);
      //  objviewalldata.deptname = emp1.dept.deptname;
      // objviewalldata.empname = emp1.empname;


      var emp1 = new ViewAllData();

      MySqlConnection con = new MySqlConnection(@"server=127.0.0.1;user id=root;pwd=n0711p2010p;database=demo;persistsecurityinfo=True");
      using (con)
      {
          con.Open();
          string query = "select emp.empname,dept.deptname from emp inner join dept on emp.deptid=dept.deptid";
          using (MySqlCommand cmd = new MySqlCommand(query, con))
          {
                MySqlDataReader dr;
                emp1.alllemp = new List<string>();
                emp1.alldept = new List<string>();
                using ( dr = cmd.ExecuteReader())
                {
                    while (dr.Read())
                    {
                        emp1.empname = dr["empname"].ToString();
                        emp1.deptname = dr["deptname"].ToString();

                        emp1.alllemp.Add(emp1.empname);
                        emp1.alldept.Add(emp1.deptname);
                    }
                }
           }
      }
      return View(emp1);


} 

查看.cshtml

@model  MvcApplication3.Models.ViewAllData

@{
    ViewBag.Title = "Data";
}

<h2>Data</h2>


<table>
    <tr>
        <th>Employee Name</th>
        <th>Depart Name</th>
    </tr>

@foreach (string item in Model.alllemp)
{ <tr>

        <td>@Html.Label(item)</td>

     @foreach (string item1 in Model.alldept)
        {
          <td>@Html.Label(item1)</td>
        } 

       </tr>  

}

</table>

这是我的输出

enter image description here

我想要像这样的输出

Employee Name Department Name
Neel          Software
Nisarg        Software
Prachi        Embeded

最佳答案

只需用简单的 for 循环替换 foreach 循环,因为无需嵌套即可生成输出:

<table>
<tr>
    <th>Employee Name</th>
    <th>Depart Name</th>
</tr>

@for (int i=0; i < Model.allemp.Count;i++)
{
<tr>

    <td>@Html.Label(Model.allemp[i])</td>

    <td>@Html.Label(Model.alldept[i])</td>


</tr>

}

关于c# - 如何在 MVC ASP .net C# 的 .cshtml 文件中使用嵌套 foreach 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50501507/

相关文章:

c# - AutoFixture 和私有(private)属性

asp.net-mvc - 如何检测 Linq to SQL 中的 Select n+1 问题?

asp.net-mvc-4 - 在 ASP.NET MVC 函数中获取查询字符串值

javascript - 在 ASP.NET MVC 中动态生成 Javascript、CSS

c# - 在 ASP.NET (MVC) 中从 CSV/Excel 导入期间标准化数据的推荐方法是什么?

c# - "Unable to read data from the transport connection"- C#

c# - 如何获取Python脚本返回值以在Visual Studio表单中使用?

asp.net-mvc - 遭劫持的Umbraco HttpPost操作未触发

c# - ASP.NET c# 中的 AJAX 错误

asp.net-mvc-3 - 从 Razor View 引用资源文件