我在用户页面上创建了一个表格,其中显示了他们所关注的所有餐馆。但是当我运行页面时,我收到错误Object reference not set to an instance of an object.
对于行
@foreach (var RestaurantSearch in Model.RestaurantSearch)
是否应该以不同的方式编写此代码?
个人资料页面代码
@foreach (var RestaurantSearch in Model.RestaurantSearch)
{
var manager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext()));
var currentUser = manager.FindById(User.Identity.GetUserId());
if (RestaurantSearch.User1ID == @currentUser.Id)
{
<tr>
<td>
@Html.DisplayFor(modelItem => RestaurantSearch.RestaurantID)
</td>
<td>
@Html.DisplayFor(modelItem => RestaurantSearch.User1ID)
</td>
<td>
@Html.ActionLink("Details", "Details", "Restaurant", new { id = RestaurantSearch.RestaurantID }, null) |
</td>
</tr>
}
}
</table>
Followviewmodel
public class Followviewmodel
{
public IEnumerable<BiteWebsite.Models.Followuser> UserSearch { get; set; }
public IEnumerable<BiteWebsite.Models.FollowRestaurant> RestaurantSearch { get; set; }
public string Name { get; set; }
public string Cuisine { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string UserName { get; set; }
}
答案 0 :(得分:4)
您的Model
或Model.RestaurantSearch
为空。您必须在Controller操作中设置它。
样品:
public ActionResult Index()
{
Followviewmodel model = new Followviewmodel();
// fill in the fields
model.RestaurantSearch = ...
return View(model);
}