我正在尝试创建一个项目,我想显示用户的详细信息,然后在表格中我想显示该用户完成的课程。当我尝试显示用户详细信息时,该用户的详细信息显示为自我使用foreach循环后他们正在采用的课程数量。如果不使用foreach,我怎么能这样做?如果从单个表中存储和检索所有数据,我可以这样做但在这个项目中我使用三个表 - 用户,课程和用户课程。 UserCourse具有UserId和CourseId的外键引用。现在我想从用户表中检索详细信息。
HomeController中:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Login(User u)
{
if (ModelState.IsValid)
{
using (DetailsEntities dc = new DetailsEntities())
{
var v = dc.Users.Where(a => a.UserName.Equals(u.UserName) && a.Password.Equals(u.Password)).FirstOrDefault();
if (v != null)
{
Session["User"] = v;
return RedirectToAction("Index", "Course");
}
}
}
return View(u);
}
CourseController:
public class CourseController : Controller
{
private DetailsEntities db = new DetailsEntities();
//
// GET: /Course/
public ActionResult Index()
{
User user = (User)Session["User"];
//var usr = db.Users.Find(user.UserId);
//int userId = (int)Session["UserId"];
var user1 = db.Users.FirstOrDefault(u => u.UserId==user.UserId);
if (Session["User"] != null)
{
var course = db.UserCourses.Where(u => u.UserId == user1.UserId);
if (user1 != null)
return View(course);
}
return View(user1);
}
}
索引:
<table border="1" align="center" height ="200px" width ="100%" @*style ="background-color: darkgray"*@>
<tr>
<th>
@Html.DisplayNameFor(model => model.User.FirstName)
</th>
<th>
@Html.DisplayNameFor(model => model.User.LastName)
</th>
<th>
@Html.DisplayNameFor(model => model.User.Address)
</th>
<th>
@Html.DisplayNameFor(model => model.User.City)
</th>
<th>
@Html.DisplayNameFor(model => model.User.Email)
</th>
<th>
@Html.DisplayNameFor(model => model.User.PhoneNo)
</th>
<th></th>
</tr>
@foreach (var item in Model)
{
<tr>
<td>
@Html.DisplayFor(modelItem => item.User.FirstName)
</td>
<td>
@Html.DisplayFor(modelItem => item.User.LastName)
</td>
<td>
@Html.DisplayFor(modelItem => item.User.Address)
</td>
<td>
@Html.DisplayFor(modelItem => item.User.City)
</td>
<td>
@Html.DisplayFor(modelItem => item.User.Email)
</td>
<td>
@Html.DisplayFor(modelItem => item.User.PhoneNo)
</td>
</tr>
}
</table>
<p>
@Html.ActionLink("Create New", "Create")
</p>
<table border="1" align="left" height ="200px" width ="300px" @*style ="background-color: darkgray"*@>
<tr>
<th>
@Html.DisplayNameFor(model => model.Course.CourseName)
</th>
</tr>
@foreach (var item in Model) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.Course.CourseName)
</td>
<td>
@Html.ActionLink("Edit", "Edit", new { id=item.Id }) |
@Html.ActionLink("Details", "Details", new { id=item.Id }) |
@Html.ActionLink("Delete", "Delete", new { id=item.Id })
</td>
</tr>
}
</table>
我知道这个问题很愚蠢,但我是新手,所以请帮助我。