我有一个表Food
,当用户在Account/register.cshtml
中注册时,我希望显示该表中的所有信息。我已经测试过在AccountController
public ActionResult Register()
{
ApplicationDbContext db = new ApplicationDbContext();
var food = db.Food.Select(x => x.Food).ToList();
return View(food);
}
我的观点register.chhtml看起来像这样
@model FoodApplication.Models.RegisterViewModel
@foreach (var item in Model)
{
@item.Food
}
在视图模型中收到我无法使用foreach的错误。
我该如何解决这个问题?
答案 0 :(得分:1)
这不是一个好方法,因为更改了默认的AccountViewModel,但您将获得所需的结果
更改AccountViewModel
public class RegisterViewModel
{
[Required]
[EmailAddress]
[Display(Name = "Email")]
public string Email { get; set; }
[Required]
[StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
[DataType(DataType.Password)]
[Display(Name = "Password")]
public string Password { get; set; }
[DataType(DataType.Password)]
[Display(Name = "Confirm password")]
[Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
public string ConfirmPassword { get; set; }
public List<Food> Products = null;
}
更改AccountController中的索引方法
public ActionResult Index()
{
return View(new RegisterViewModel()
{
Products = db.Food.Select(x => x.Food).ToList()
});
}
添加到Register.cshtml
<ul>
@foreach (var z in Model.Products)
{
<li>@z.id</li>
<li>@z.name</li>
}
</ul>