c# - 返回 View (型号 : MyModel); equivalent in ASP.Net Core Razor Pages

标签 c# asp.net asp.net-core razor-pages

我希望在 ASP Razor Pages 中看到类似 return Page(model: MyModel); 的内容。而不是 Page();没有参数。

所以我可以返回没有 PageModel 类的页面。

我不能使用 TempData,因为 MyModel 是一个复杂类型。

如何获得与 ASP MVC 相同的功能 return View(model: MyModel);

请注意,这个问题不是针对所有 MVC 开发人员的,而是针对经验丰富的 ASP.Net Core Razor Page 开发人员的。 谢谢。

最佳答案

好的,这里是一个简单的 Restaurant 应用程序的示例。 如您所见,Restaurant 对象是 DetailModel 中的一个属性。一旦我将它设置在 OnGet() 方法中。我能够在我的 Razor 页面 View 中访问它的数据。

public class DetailModel : PageModel
{
    private readonly IRestaurantData restaurantData;

    [TempData]
    public string Message { get; set; }

    public Restaurant Restaurant { get; set; }

    public DetailModel(IRestaurantData restaurantData)
    {
        this.restaurantData = restaurantData;
    }

    public IActionResult OnGet(int restaurantId)
    {
        Restaurant = restaurantData.GetById(restaurantId);
        if(Restaurant == null)
        {
            return RedirectToPage("./NotFound");
        }
        return Page();
    }
}

以及页面的 View 。

@page "{restaurantId:int}"

@model MyProject.Pages.Restaurants.DetailModel
@{
    ViewData["Title"] = "Detail";
}

<h2>@Model.Restaurant.Name</h2>
<div>
    Id: @Model.Restaurant.Id
</div>
<div>
    Location: @Model.Restaurant.Location
</div>
<div>
    Cuisine: @Model.Restaurant.Cuisine
</div>

@if(Model.Message != null)
{
    <div class="alert alert-info">@Model.Message</div>
}

<a asp-page="./List" class="btn btn-default">All Restaurants</a>

真正的 Razor 页面作为一个页面工作,因此您不必返回模型。您只需绑定(bind)它,您就可以在页面内部访问。

这有意义吗? 另请阅读 DOCS 以获取更多信息:https://learn.microsoft.com/en-us/aspnet/core/razor-pages/?view=aspnetcore-3.1&tabs=visual-studio

关于c# - 返回 View (型号 : MyModel); equivalent in ASP.Net Core Razor Pages,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59225214/

相关文章:

c# - 去除位于 Dictionary 中的 List<string> 中的空格

c# - 带有 CaSTLe windsor 的 WCF Web 服务客户端

c# - 多应用服务器环境和 Memcached 安全

c# - 使用 ViewBag 中的列表选择 TagHelper

c# - 如何拆分文本文件并使用整数?

c# - 使用 StringBuilder 和 DataTable,当只有一行时,如何在不中断的情况下返回三列中的多行?

c# - 在 System.ComponentModel 默认值属性中将 DateTime 属性的默认值设置为 DateTime.Now

c# - Asp.net 服务器应用程序正在本地主机上运行,​​但不在 Azure 中运行(未处理的异常渲染组件 : ExpectedJsonTokens)

asp.net-core - ASP.Net Core 最大UrlLength

iis - 如何允许同一网络中的其他设备使用 IP :Port? 访问 Visual Studio for Mac Web API 项目