Skip to main content
 首页 » 编程设计

c#之我如何让我的观点识别我的对象

2024年02月06日10linjiqin

我已经创建了一个 View ,我想用它来显示从数据库中提取并在我的操作中传递给 View 的结果。当我创建 View 时,我没有告诉它我想传入哪些对象,所以我尝试手动添加它们,但 View 似乎无法识别它们。

这是我的结果 View ,顶行是我要添加的内容,但 VS 无法识别它。所以空格是红色的(无法识别),item.Name 和 item.description 是红色的

@spaces IQueryable<GiftExchange.Core.Models.Space.YogaSpace> 
 
 @{ 
   ViewBag.Title = "Results"; 
   Layout = "~/Views/Shared/_Layout.cshtml"; 
} 
 
<h3>Search Results</h3> 
@using (Html.BeginForm("Results", "Home", FormMethod.Get)) 
{ 
    <p> 
    @Html.TextBox("Location") <input value='Search' type="submit" /> 
    </p> 
} 
 
 
<table border="1"> 
<tr> 
    <th> 
        @Html.DisplayNameFor(spaces => spaces.Name) 
    </th> 
    <th> 
        @Html.DisplayNameFor(spaces => spaces.Description) 
    </th> 
</tr> 
 
 
 
@foreach (var item in spaces) 
{ 
    <tr> 
        <th> 
            @Html.DisplayFor(modelItem => item.Name) 
        </th> 
        <th> 
            @Html.DisplayFor(modelItem => item.Description) 
        </th> 
    </tr> 
} 
 
</table> 

这是我的 Action

[AllowAnonymous] 
    public ActionResult Results(string searchTerm) 
    { 
        IQueryable<YogaSpace> spaces; 
        using (var repo = new YogaSpaceRepository()) 
        { 
            spaces = repo.All; 
        } 
 
        return View(spaces); 
    } 

请您参考如下方法:

在 View 的第一行,将 @spaces 切换为 @model。

然后在您想使用它的地方,使用 Model 而不是 spaces。

有关更多详细信息,请在谷歌上搜索“强类型 View ”。