我正在创建一个应用程序,我在其中使用Mysql数据库从两个不同的表中检索数据。我得到了正确的数据,但问题是,当我尝试使用foreach循环在视图上显示它时,数据不会以正确的方式显示。
这是我的代码:
控制器
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);
}
View.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>
这是我的输出
我想输出
Employee Name Department Name
Neel Software
Nisarg Software
Prachi Embeded
答案 0 :(得分:2)
只需用简单的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>
}
答案 1 :(得分:0)
错误导致代码如下:
emp1.alllemp.Add(emp1.empname);
emp1.alldept.Add(emp1.deptname);
也许您可以按如下方式声明ViewAllData:
public List<VO> emps {get;set;}
public class VO
{
public string empname {get;set;}
public string deptname {get;set;}
}
然后,修改数据层中的代码。
using ( dr = cmd.ExecuteReader())
{
while (dr.Read())
{
VO vo = new VO();
vo.empname = dr["empname"].ToString();
vo.deptname = dr["deptname"].ToString();
emp1.emps.Add(vo);
}
}
然后,修改视图层中的代码。
@foreach (string item in Model.emps)
{
<tr>
<td>@Html.Label(item.empname)</td>
<td>@Html.Label(item.deptname)</td>
</tr>
}