如何在MVC视图(CSHTML)中展示DisplaceModel列表对象
解决MVC视图中遍历展示DisplaceModel列表的问题
我来帮你搞定这个视图遍历的问题,咱们一步步来修正你的代码:
首先,修正模型声明问题
你在Controller里传递的是单个DisplaceModelInformation实例,但视图顶部错误地声明了IEnumerable<FindLocation.Models.DisplaceModelInformation>(这是集合类型)。第一步要把模型声明改成单个对象:
@model FindLocation.Models.DisplaceModelInformation
然后,修正列表遍历逻辑
你的DisplaceModelInformation类里包含Dispaylist(注意这里你拼写错了,建议改成DisplayList避免后续混淆)这个List<DisplaceModel>集合,所以你需要遍历的是Model.Dispaylist,而不是Model本身。
完整修正后的视图代码
@model FindLocation.Models.DisplaceModelInformation @using (Html.BeginForm()) { <table> <thead> <tr> <th>NAME</th> <th>ADDRESS</th> <th>RATING</th> <th>PHOTO</th> <!-- 可选:如果要展示图片可以添加这列 --> </tr> </thead> <tbody> @if (Model.Dispaylist != null && Model.Dispaylist.Count > 0) { @foreach (var place in Model.Dispaylist) { <tr> <td>@place.Name</td> <td>@place.Address</td> <td>@(place.Rating ?? "No rating available")</td> <!-- 处理Rating为空的情况 --> <!-- 可选:如果有图片引用,展示图片(以Google Places图片API为例) --> <td> @if (!string.IsNullOrEmpty(place.PhotoReference)) { <img src="https://maps.googleapis.com/maps/api/place/photo?maxwidth=@place.Width&photoreference=@place.PhotoReference&key=YOUR_API_KEY" alt="@place.Name" width="@place.Width" height="@place.Height" /> } else { <span>No photo</span> } </td> </tr> } } else { <tr> <td colspan="4">No results found</td> </tr> } </tbody> </table> }
额外小提示
- 把
Dispaylist的拼写修正为DisplayList(类和Controller里的代码都要改),避免拼写错误导致的潜在问题 - 增加空值判断(比如Rating为空、无图片的情况),可以让页面展示更友好
内容的提问来源于stack exchange,提问作者padmanaban padmaraj
相关产品推荐
相关产品推荐

